简体   繁体   中英

Java PrintWriter printing multiple blank lines at the beginning of each file

I have used PrintWriter for long time and I have never encounted with this problem. See below

When I open the csv file using excel the first element of the headerline disapeared. 在此处输入图片说明

To further investigate, I found a couple of blank lines inserted at the beginning when opening it using text file.

在此处输入图片说明

below is my code:

print header line:

public void printHubInboundHeader() {
    try {
        StringBuilder sb = new StringBuilder();
        String headingPart1 = "Inbound_Hub, Date, Time,";
        String headingPart2 = "Weight";
                    
        sb.append(headingPart1+headingPart2);
        System.out.println(sb);
        FileWriter.writeFile(sb.toString(),"filepath");
    }
    catch(Exception e) {
        System.out.println("Something wrong when writting headerline");
        e.printStackTrace();
    }
    
}

print actual data:

    public void printHubSummary(Hub hub, String filePath) {
        
        try {
            StringBuilder sb = new StringBuilder();   
            
            String h = hub.getHub_code();
            String date = Integer.toString(hub.getGs().getDate());
            String time = hub.getGs().getHHMMFromMinute(hub.getGs().getClock());
            String wgt = Double.toString(hub.getIb_wgt());

                    
            sb.append(h+","+date+","+time+","+wgt);
//          System.out.println("truck print line: " + sb);
            FileWriter.writeFile(sb.toString(),filePath);
        }
        
        catch (Exception e) {
            System.out.println("Something wrong when outputing truck summary file!");
            e.printStackTrace();        
        }
    }

the file writer code:

public class FileWriter {
    private static String filenameTemp;

    public static boolean creatFile(String name) throws IOException {
        boolean flag = false;
        filenameTemp = name + "";
        System.out.println("write to file: "+filenameTemp);
        File filename = new File(filenameTemp);
        if (!filename.exists()) {
            filename.createNewFile();
            flag = true;
        }
        else {
            filename.delete();
            filename.createNewFile();
            flag = true;
        }
        return flag;
    }

    public static boolean writeFile(String newStr, String filename) throws IOException {
        boolean flag = false;
        String filein = newStr + "\r\n";
        String temp = "";

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            File file = new File(filename);
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();

            for (int j = 1; (temp = br.readLine()) != null; j++) {
                buf = buf.append(temp);
                buf = buf.append(System.getProperty("line.separator"));
            }
            buf.append(filein);

            fos = new FileOutputStream(file);
            byte[] unicode = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
            fos.write(unicode);
            pw = new PrintWriter(fos);
            
            pw.write(buf.toString().toCharArray());
            pw.flush();
            flag = true;
        } catch (IOException e1) {
            throw e1;
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return flag;
    }
    
    public static void setFileName(String fileName){
        filenameTemp = fileName;
    }

}

I don't know if this is the only problem with your code, but every call to your FileWriter.writeFile adds a new Byte Order Marker to the file. This means you end up with several markers in the file, and this may confuse some tools.

To remove the extra BOM in FileWriter.writeFile , you can use the deleteCharAt method:

    ...
    buf = buf.append(System.getProperty("line.separator"));
}
if (buf.length() > 0 && buf.charAt(0) == '\uFEFF') {
    buf.deleteCharAt(0);
}
buf.append(filein);

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