2013-04-30 96 views
0

我向文本文件写入了数据,但文件中的数据不正确。我认为这是OutpubStream的问题,因为我在前面的步骤中显示数据,并且它们是正确的。来自OutputStream(Java)的文件中的数据输入不正确

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

} 

输入数据FILE1.TXT FILE2.TXT

3 strahge tokens plus !-68DU 

感谢答案

10 
56 
2 
33 
45 
21 
15 
68 
54 
85 

输出数据,原谅我的英语。

+2

我看了你的问题,大约3次,我仍然不知道什么是所需的输出 – 2013-04-30 16:30:39

+0

难道是一个字节顺序标记? – Fildor 2013-04-30 16:40:03

回答

-1

你可以考虑转化的字符串转换成字节码:

System.out.println(r);// display data-all be correct 
String line = (String.valueOf(r) + "\n"); 
os.write(line.getBytes()); 
+0

我认为输入的输出 ... 那么,为什么不把数据转换成字符串,然后写出它的字节呢 – fGo 2013-04-30 17:09:19

+0

谢谢,这是接近真实的。在这个例子中,我只想使用Java内部方法。 – Vakhrushev 2013-04-30 17:25:54

+0

为什么要投票? – fGo 2013-05-23 11:39:52

0

使用FileWriter的,而不是作为FileOutputStream中你的数据是文本,你可能想使用字符

2

线

os.write(r); 

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

使用类似:

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

,你可能希望新行:

os.write(String.valueOf(r)+"\n"); 
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(); 
相关问题