incorrect data input in file from an OutputStream( Java ) - java

I wrote a data to text file, but data in file are incorrect. I think it is problem with OutpubStream, because I display data on previous steps, and they were correct.
private void Output(File file2) {
// TODO Auto-generated method stub
OutputStream os;
try {
os = new FileOutputStream(file2); //file2-it is my output file, all normal with him
Iterator<Integer> e=mass.iterator();
int r=0;
while(e.hasNext()){
r=e.next();
System.out.println(r);//display data-all be correct
os.write(r);//I think problem create in this step/
}
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Input data file1.txt
10
56
2
33
45
21
15
68
54
85
Output data file2.txt
3 strahge tokens plus !-68DU
thanks for answers, excuse me for my english.

The line
os.write(r);
Writes the binary value of integer r to the file.
Use something like:
os.write(String.valueOf(r));
and you probably want new lines:
os.write(String.valueOf(r)+"\n");

FileOutputStream is used to write binary raw Data. As specified in document :
FileOutputStream is meant for writing streams of raw bytes such as
image data. For writing streams of characters, consider using
FileWrite
Since you are writing integers to the file so what you need is text-output Stream like PrintWriter. It can be used in your code as follows:
PrintWriter pw = new PrintWriter(file2); //file2-it is my output file, all normal with it
Iterator<Integer> e=mass.iterator();
int r=0;
while(e.hasNext()){
r=e.next();
pw.print(r);
pw.println();//for new line
}
pw.close();

use FileWriter instead of FileOutputStream as your data is text and you probably want to use a stream of characters

you could consider transforming the string into a bytecode:
System.out.println(r);// display data-all be correct
String line = (String.valueOf(r) + "\n");
os.write(line.getBytes());

Related

Reading and writing an array to file

Hello there stackoverflow .
The thing im tring to make work is saving some information from an array to a file and then reading it back to another array . The goal is to save themes (hex color codes of user) so they can share their theme or backing it up .
Here is my code to write the array to file
String filename = "my.theme";
String[] numbers = new String[] {"1, 2, 3"};
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
for (String s : numbers) {
outputStream.write(s.getBytes());
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
The output is a file with :
1,2,3
Now how can i read it back to another array ?
For my goal . Can you suggest anything other then using this method ? Its ok to save as a xml too . Thanks :)
You can use a Scanner class, this small example will help you get started:
String input = "1,2,3";
Scanner scn = new Scanner(input); // Scanner also accepts a file!
scn.useDelimiter(","); // Since the integers are "comma" separated.
while(scn.hasNext())
{
System.out.println(scn.nextInt()); // here you can store your integers back into your array
}
scn.close();
OUTPUT:
1
2
3

Why is my DataInputStream only reading 114 bytes?

I'm trying to extract a file from my jar and copying it into the temp directory.
To read the file within the jar, I am using a DataInputStream, to write the file in the temp directory, I am using a DataOutputStream.
The file I am trying to extract has a file size of 310 kilobytes, my copied file only contains 114 bytes after I've called my method (this is also the number of bytes my method prints to the console).
Here is my method:
private static void extractFile(String pathInJar, String fileToCopy) {
File outputFile = new File(System.getProperty("java.io.tmpdir") + "/LDEngine/"+fileToCopy);
boolean couldDirsBeCreated = outputFile.getParentFile().mkdirs();
if(couldDirsBeCreated && !outputFile.exists()) {
int x;
int actualBytesRead = 0;
byte[] tmpByteArray = new byte[4096];
try(
DataOutputStream output = new DataOutputStream(new FileOutputStream(outputFile));
DataInputStream in = new DataInputStream(LibLoader.class.getResourceAsStream("/libs/natives/"+pathInJar))
){
while((x=in.read(tmpByteArray)) != -1) {
output.write(tmpByteArray);
actualBytesRead += x;
}
} catch(Exception e) {
System.err.println("Fatal error: Could not write file!");
System.exit(1);
}
System.out.println(actualBytesRead);
}
}
The file I am trying to copy is a .dll, so it's binary data I'm dealing with.
The question is why is this happening and what am I doing wrong?
This does not explain why your method stops so soon, but you need to take care of it or you will have an even stranger problem with the result data being completely garbled.
From the APi doc of DataInputStream.read():
Reads some number of bytes from the contained input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer.
You need to use that return value and call the write() method that takes and offset and length.

Reading a binary file into ArrayList in Java

I want to read binary file in java. I have 153(1.bin, 2.bin...153.bin) bin file. I must read that. I thought that I must use ArrayList for buffering. But I could not do that. How can I do this ?
After some research, I found that way in this title(Reading a binary input stream into a single byte array in Java). There is code like below in this title.
StringBuilder sb = new StringBuilder();
String fileName = "/path/10.bin";
byte[] buffer;
try {
buffer = Files.readAllBytes(Paths.get(fileName));
for(byte b : buffer){
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Is it true way for my question or do I must use Arraylist for buffering ? If I use single byte array for buffering, do I must clear the buffer for the other binary files.
Edit : 153 unit means 153 file(1.bin,2.bin ... 153.bin)
Your question is unclear. For one, you don't tell what those "units" are, how long they are etc. Second, all your code does is dump the contents of the file in hexadecimal.
What I suggest you do here is map the file into memory and use a class to wrap that around, and make it implement Closeable.
See FileChannel.open() and FileChannel.map(). Please note however that it is unsafe to map more than 1 GiB in memory. This is not a "real" mmap().
I'm not sure what you mean by "units". Byte data is read something like that:
File f = new File ("File.txt");
FileInputStream fis = new FileInputStream (f);
byte[] bytes = new byte[(int) f.length ()];
fis.read (bytes, 0, (int) f.length () );
Make sure your File is not too big.
I'm assuming a unit is one byte. Is this correct?
An ArrayList is not appropriate for byte buffering. It is a wrapper class for an array that implements the List interface (by which most of it's power is defined.)
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
If you simply want to read bytes in from a file, you could use FileInputStream.
http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html
Here's a simple example that reads input from a file containing "hello world!"
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Input {
public static void main(String[] args) throws FileNotFoundException, IOException {
try (FileInputStream in = new FileInputStream("test.txt")) {
int c;
while ( (c = in.read()) != -1 )
System.out.print((byte)c + " ");
}
}
}
Output in bytes: 104 101 108 108 111 32 119 111 114 108 100 33 13 10

Strange behavior in writing to file

I was trying some basic Java I/O operations, I try to run the below code :
public static void main(String[] args) {
File file = new File("fileWrite2.txt"); // create a File object
try {
FileWriter fr = new FileWriter(file);
PrintWriter pw = new PrintWriter(file); // create a PrintWriter that will send its output to a Writer
BufferedWriter br = new BufferedWriter(fr);
br.write("sdsadasdsa");br.flush();br.append("fffff");br.flush();
pw.println("howdy"); // write the data
pw.println("folks");
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When I run the above I get the following output in the file created :
howdy
folks
f
Can anyone explain why the 'f' is coming in the last line ?
The f comes from the left over string of br.append("fffff"); which was written in the file by the BufferedWriter.
Since both BufferedWriter and PrintWriter write to the same file, the contents written by the PrintWriter overwrite the contents written by the BufferedWriter.
But seems the no. of bytes written by PrintWriter fall short by 1 to completely overwrite the data written by BufferedWriter and thus you get the f.
If you change this br.append("fffff"); to br.append("ffffg");, you can see that the g is now left over. Alternatively, changing pw.println("folks"); to pw.println("folks1"); will show that the previously written data is now completely overwritten by the PrintWriter.
All this confusion is because of having 2 different writers for the same file object which is the cause of the problem. As #Boris pointed out, have just 1 writer for a file object.
Note: Another interesting thing to test out would be to move the second br.flush(); after the pw.flush();.
// br.flush(); // moved from here
pw.println("howdy"); // write the data
pw.println("folks");
pw.flush();
br.flush(); // to here
You are writing 15 characters on the bufferedwriter by doing this
`
br.write("sdsadasdsa");
br.flush();
br.append("fffff");`
But when you are writng on printWriter, it overwrites the content of the file
this time you are writing
pw.println("howdy"); // write the data
pw.println("folks");
which is 10 characters only with two new line \n which takes 2 bytes since we use println because \n in windows will transform to \r\n . So total of 14.
so 1 character remains there which is f
In your code the following steps are executed.
1 When
br.write("sdsadasdsa");br.flush();br.append("fffff");br.flush();
is executed.
The file content will be
sdsadasdsafffff
2 when
pw.println("howdy"); is calling.
String howdy override the first 5 character sdsad and a new line terminates the line. In txt, 2 characters are needed \r\n, this will over write another 2 character .Then the file content will be as follows:
howdy
dsafffff
3 when
pw.println("folks");
is executed.
Since it is not called flush() method in step#2. String folks will over write the second line content in file. and a new line to over write another 2 characters.
Then the following content will be stored in file:
howdy
folks
f

Why does out.write() alter int values in Java?

I'm trying to output some data to file in Java and do not understand why when I run this code...
try {
File file = new File("demo.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
int i = 127;
int j = 128;
System.out.println(Integer.toHexString(i));
System.out.println(Integer.toHexString(j));
out.write(i);
out.write(j);
out.close();
} catch (IOException e) {}
...the following is output to the console log:
7f
80
but when I open the file demo.txt with a hex editor I see the bytes 7f and 3f. Why does out.write() output most int values correctly (example 127) but alters others (example 128)? How can I write the data to the file straight?
FileWriter should be used to write character streams. If you are trying to write binary data, then a FileOutputStream is appropriate. If you replace your FileWriter with a FileOutputStream and your BufferedWriter with a BufferedOutputStream you will find that the data is written as you'd expect.
FileWriter is character and encoding-aware which means that it may transform data that you pass through it to match a character encoding. But to be honest I don't know exactly what transformation is going on here.

Categories

Resources