I tried below code to write a map into file and read it:
#After
public void init(Scenario scenario){
hm.put(testNames,scenario.getStatus());
// to write code into file
try {
File fileOne=new File("file.txt");
FileOutputStream fos=new FileOutputStream(file,true);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(hm);
oos.flush();
oos.close();
fos.close();
;
} catch(Exception e) {}
}
//to read the file(in other java program)
try {
File toRead=new File("file.txt");
FileInputStream fis=new FileInputStream(toRead);
ObjectInputStream ois=new ObjectInputStream(fis);
HashMap<String,io.cucumber.java.Status> mapInFile=(HashMap<String,io.cucumber.java.Status>)ois.readObject();
ois.close();
fis.close();
for(Map.Entry<String,io.cucumber.java.Status> m :mapInFile.entrySet()){
System.out.println(m.getKey()+" : "+m.getValue());
}
The code to write to file is wrapped in #After.
I am able to write into file but getting only 1 key value pair as O/P
Related
It throws eof exception in line 10 when I execute the following code. It seems that it cannot execute the readLong method. What should I do?
try (DataOutputStream dataOutputStream=new DataOutputStream(new BufferedOutputStream(new
FileOutputStream("1.dat")));
DataInputStream dataInputStream=new DataInputStream(new BufferedInputStream(new
FileInputStream("C:\\Users\\Asus\\IdeaProjects\\Example" +
"\\1.dat")))){
dataOutputStream.writeLong(123);
dataOutputStream.writeChar('D');
dataOutputStream.writeUTF("Hello!");
System.out.println(dataInputStream.readLong());//exception occurse here
System.out.println(dataInputStream.readChar());
System.out.println(dataInputStream.readUTF());
}catch (IOException e){
e.printStackTrace();
}
the problem you are reading the file before writing on it. when you read the file it was empty. also the data are not saved to the file until the stream is closed. so if you want to read the written values you should close the input stream and then read the file.
also be careful that the output stream file path is different than the input stream
here an example:
try ( DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("1.dat")))) {
dataOutputStream.writeLong(123);
dataOutputStream.writeChar('D');
dataOutputStream.writeUTF("Hello!");
dataOutputStream.close();
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream("1.dat")));
System.out.println(dataInputStream.readLong());
System.out.println(dataInputStream.readChar());
System.out.println(dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
I've created a Huffman coding algorithm, and then I wrote binary code in String and put it in binary file using FileOutputStream and DataOutputStream.
But now I cant understand how to read it? I need to get 1 and 0 sequence from binary file.
There is no method like .readString() in DataInputStream
try{
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary", "*.bin"));
FileOutputStream fileOutputStream = new FileOutputStream(fileChooser.showSaveDialog(window));
DataOutputStream outputStream = new DataOutputStream(fileOutputStream);
outputStream.writeChars(Main.string_ready_encode);
}catch (IOException e){
e.printStackTrace();
}
Main.string_ready_encode contains ready sequence
The problem with your writing code is that you have specified no file format. We now can only read the file if we know how many bytes it has. If you do know that, you can read it by doing the following:
try (DataInputStream stream = new DataInputStream(new FileInputStream(f))) {
byte[] bytes = new byte[NUMBER_OF_BYTES];
stream.read(bytes);
String content = new String(bytes);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
But I would actually advise you to rewrite you file with some known file format, like so:
try (Writer writer = new OutputStreamWriter(new FileOutputStream(f), Charsets.UTF_8)) {
writer.write(Main.stringReadyEncode, 0, Main.stringReadyEncode.length());
} catch (IOException x) {
e.printStackTrace();
}
And read it like you would read any other file:
try (BufferedReader r = Files.newBufferedReader(f.toPath(), Charsets.UTF_8)) {
String line;
while((line = r.readLine()) != null) {
// do whatever you want with line
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Just make sure to replace Charsets.UTF_8 with whatever encoding you used while writing to the file.
Hi im trying to save my ArrayList of objects to a file when onPause() and/or onStop() are called and then have the arrayList read from that file after the app has been killed and relaunched. Ive tried a load of different methods but none seem to work, currently this is what I have.
my code to Write :
try{
FileOutputStream fout = openFileOutput(FILENAME, 0);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(toDos);
oos.close();
}
catch (Exception e){
e.printStackTrace();
}
My code to Read :
try{
FileInputStream streamIn = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(streamIn);
if(ois.readObject() != null) {
list = (ArrayList<Object>) ois.readObject();
ois.close();
}
}
catch (Exception e){
e.printStackTrace();
}
"FILENAME" is a variable that holds the string "data.txt"
toDos is the name of the arrayList, it is a field at the top of the Activity, it is an ArrayList of object Object which is Serializable.
Not sure what im doing wrong here, and I cant tell if its writing at all or not or where the issue might be.
You are getting an EOFException because you are reading in the object twice; once when you're checking the if statement, and once again inside the if statement. Change your code to something like this:
FileInputStream streamIn = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(streamIn);
ToDoObject tmp = (ArrayList<ToDoObject>) ois.readObject();
ois.close();
if(tmp != null) {
toDos = tmp;
}
This code accomplishes the same thing but reads from the file a single time.
Is there any way to create a java.io.File object from an java.io.InputStream ?
My requirement is reading the File from a RAR . I am not trying to write a temporary File, I have a file inside RAR archive which I am trying to read.
You need to create new file and copy contents from InputStream to that file:
File file = //...
try(OutputStream outputStream = new FileOutputStream(file)){
IOUtils.copy(inputStream, outputStream);
} catch (FileNotFoundException e) {
// handle exception here
} catch (IOException e) {
// handle exception here
}
I am using convenient IOUtils.copy() to avoid manual copying of streams. Also it has built-in buffering.
In one line :
FileUtils.copyInputStreamToFile(inputStream, file);
(org.apache.commons.io)
Since Java 7, you can do it in one line even without using any external libraries:
Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);
See the API docs.
Create a temp file first using org.apache.commons.io.
File tempFile = File.createTempFile(prefix, suffix);
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
return tempFile;
Easy Java 9 solution with try with resources block
public static void copyInputStreamToFile(InputStream input, File file) {
try (OutputStream output = new FileOutputStream(file)) {
input.transferTo(output);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
java.io.InputStream#transferTo is available since Java 9.
If you do not want to use other libraries, here is a simple function to copy data from an InputStream to an OutputStream.
public static void copyStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
Now, you can easily write an Inputstream into a file by using FileOutputStream-
FileOutputStream out = new FileOutputStream(outFile);
copyStream (inputStream, out);
out.close();
If you are using Java version 7 or higher, you can use try-with-resources to properly close the FileOutputStream. The following code use IOUtils.copy() from commons-io.
public void copyToFile(InputStream inputStream, File file) throws IOException {
try(OutputStream outputStream = new FileOutputStream(file)) {
IOUtils.copy(inputStream, outputStream);
}
}
We have an application which requires us to read data from a file (.dat) dynamically using deserialization. We are actually getting first object and it throws null pointer exception and "java.io.StreamCorruptedException:invalid type code:AC" when we are accessing other objects using a "for" loop.
File file=null;
FileOutputStream fos=null;
BufferedOutputStream bos=null;
ObjectOutputStream oos=null;
try{
file=new File("account4.dat");
fos=new FileOutputStream(file,true);
bos=new BufferedOutputStream(fos);
oos=new ObjectOutputStream(bos);
oos.writeObject(m);
System.out.println("object serialized");
amlist=new MemberAccountList();
oos.close();
}
catch(Exception ex){
ex.printStackTrace();
}
Reading objects:
try{
MemberAccount m1;
file=new File("account4.dat");//add your code here
fis=new FileInputStream(file);
bis=new BufferedInputStream(fis);
ois=new ObjectInputStream(bis);
System.out.println(ois.readObject());
**while(ois.readObject()!=null){
m1=(MemberAccount)ois.readObject();
System.out.println(m1.toString());
}/*mList.addElement(m1);** // Here we have the issue throwing null pointer exception
Enumeration elist=mList.elements();
while(elist.hasMoreElements()){
obj=elist.nextElement();
System.out.println(obj.toString());
}*/
}
catch(ClassNotFoundException e){
}
catch(EOFException e){
System.out.println("end");
}
catch(Exception ex){
ex.printStackTrace();
}
After you read an object from the input stream, the stream points to the next object.
Try (without reading from ois before):
MemberAccount m1 = null;
while( (m1=ois.readObject()) != null){
System.out.println(m1.toString());
}
The grammar for serialized objects is defined as:
stream:
magic version contents
By using the append option (new FileOutputStream(file,true);) you create a file with this data:
stream:
magic version contents magic version contents magic version contents ....
This data does not conform to the specification and can't be decoded by ObjectInputStream.