简体   繁体   English

使用PrintWriter和DataOutputStream在Java中写入同一文件

[英]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. 我必须同时编写PrintWriterDataOutputStream才能将数据打印到我的文件中。 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. 切勿将WriterOutputStream混合使用,因为它们有不同的用途,实际上是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM