[英]Using PrintWriter and DataOutputStream to write in same file in java
I have to write both PrintWriter
and DataOutputStream
to print data onto my file. 我必须同时编写
PrintWriter
和DataOutputStream
才能将数据打印到我的文件中。 But PrintWriter
is getting printed earlier than DataOutputStream
though it comes after DataOutputStream
in code. 但
PrintWriter
是越来越此前打印比DataOutputStream
虽然谈到后DataOutputStream
中的代码。
Part of code: 部分代码:
import java.io.*;
import java.util.*;
public class file {
public static void main(String[] args) {
DataOutputStream dos=null;
PrintWriter pw=null;
try {
File f=new File("file.txt");
dos=new DataOutputStream(new FileOutputStream(f));
pw=new PrintWriter(f);
Scanner b=new Scanner(System.in);
for(int i=0;i<=4;i++) {
int h=b.nextInt();
b.nextLine();
dos.writeInt(h);
String s=b.nextLine();
int l=s.length();
dos.writeBytes(s);
pw.println();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if(dos!=null)
try {
dos.close();
} catch(IOException e) {
e.printStackTrace();
}
pw.flush();
}
}
}
new line from pw is getting printed first and then data from dos.write();
首先打印来自pw的新行,然后打印来自
dos.write();
数据dos.write();
how to avoid this?? 如何避免这种情况? and make it get in order?
并使其井然有序?
Never mix a Writer
and an OutputStream
as they are used for different purpose, indeed a Writer
is used to generate a text file (readable by a human being) and an OutputStream
is used to generate a binary file (not readable by a human being), use only one of them according to your requirements. 切勿将
Writer
和OutputStream
混合使用,因为它们有不同的用途,实际上是Writer
用于生成文本文件(人类可读),而OutputStream
用于生成二进制文件(人类不可读) ,请根据您的要求仅使用其中之一。
Assuming that you decide to use only the DataOutputStream
simply replace pw.println()
with something like dos.write(System.lineSeparator().getBytes(StandardCharsets.US_ASCII))
to write the line separator into your file with your OutputStream
. 假设您决定只使用
DataOutputStream
只需用dos.write(System.lineSeparator().getBytes(StandardCharsets.US_ASCII))
类的东西替换pw.println()
dos.write(System.lineSeparator().getBytes(StandardCharsets.US_ASCII))
即可将行分隔符与OutputStream
写入文件中。 However please note that in a binary file adding a line separator doesn't really make sense since the file is not meant to be read by a human being. 但是请注意,在二进制文件中,添加行分隔符实际上没有任何意义,因为该文件并不意味着人类可以读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.