0

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.

4

4 回答 4

2

线

os.write(r);

将整数 r 的二进制值写入文件。

使用类似的东西:

os.write(String.valueOf(r));

你可能想要新的线路:

os.write(String.valueOf(r)+"\n");
于 2013-04-30T16:33:52.470 回答
1

FileOutputStream用于写入二进制原始数据。如文件中所述:

FileOutputStream 用于写入原始字节流,例如图像数据。对于写入字符流,请考虑使用 FileWrite

由于您正在将整数写入文件,因此您需要的是文本输出流,例如PrintWriter. 它可以在您的代码中使用,如下所示:

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();
于 2013-04-30T17:07:42.917 回答
0

使用 FileWriter 而不是 FileOutputStream 因为您的数据是文本并且您可能想要使用字符流

于 2013-04-30T16:32:13.373 回答
-1

您可以考虑将字符串转换为字节码:

System.out.println(r);// display data-all be correct
String line = (String.valueOf(r) + "\n");
os.write(line.getBytes());
于 2013-04-30T17:05:34.137 回答