Carriage Return\Line feed in Java

后端 未结 6 918
滥情空心
滥情空心 2020-12-12 21:46

I have created a text file in Unix environment using Java code.

For writing the text file I am using java.io.FileWriter and BufferedWriter.

6条回答
  •  萌比男神i
    2020-12-12 22:42

    Encapsulate your writer to provide char replacement, like this:

    public class WindowsFileWriter extends Writer {
    
        private Writer writer;
    
        public WindowsFileWriter(File file) throws IOException {
            try {
                writer = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-15");
            } catch (UnsupportedEncodingException e) {
                writer = new FileWriter(logfile);
            }
        }
    
        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
            writer.write(new String(cbuf, off, len).replace("\n", "\r\n"));
        }
    
        @Override
        public void flush() throws IOException {
            writer.flush();
        }
    
        @Override
        public void close() throws IOException {
            writer.close();
        }
    
    }
    

提交回复
热议问题