Java PrintWriter 在每个文件的开头打印多个空行

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

我用PrintWriter很久了,从来没有遇到过这个问题。见下文

当我使用 excel 打开 csv 文件时,header 行的第一个元素消失了。

为了进一步调查,我发现使用文本文件打开它时在开头插入了几个空行。

下面是我的代码:

打印header行:

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

打印实际数据:

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

文件编写器代码:

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

}

我不知道这是否是您的代码的唯一问题,但每次调用您的 FileWriter.writeFile 都会向文件添加一个新的字节顺序标记。这意味着您最终会在文件中使用多个标记,这可能会混淆一些工具。

要删除FileWriter.writeFile中多余的BOM,可以使用deleteCharAt方法:

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