简体   繁体   中英

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. But PrintWriter is getting printed earlier than DataOutputStream though it comes after DataOutputStream in code.

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

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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