Vakhrushev
Vakhrushev

Reputation: 105

incorrect data input in file from an OutputStream( 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.

Upvotes: 0

Views: 329

Answers (4)

Vishal K
Vishal K

Reputation: 13066

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();

Upvotes: 1

fGo
fGo

Reputation: 1146

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());

Upvotes: -1

Chris Gerken
Chris Gerken

Reputation: 16392

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");

Upvotes: 2

mlwacosmos
mlwacosmos

Reputation: 4541

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

Upvotes: 0

Related Questions