Carriage Return\Line feed in Java

后端 未结 6 926
滥情空心
滥情空心 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条回答
  •  佛祖请我去吃肉
    2020-12-12 22:18

    Java only knows about the platform it is currently running on, so it can only give you a platform-dependent output on that platform (using bw.newLine()) . The fact that you open it on a windows system means that you either have to convert the file before using it (using something you have written, or using a program like unix2dos), or you have to output the file with windows format carriage returns in it originally in your Java program. So if you know the file will always be opened on a windows machine, you will have to output

    bw.write(rs.getString(1)==null? "":rs.getString(1));
    bw.write("\r\n");
    

    It's worth noting that you aren't going to be able to output a file that will look correct on both platforms if it is just plain text you are using, you may want to consider using html if it is an email, or xml if it is data. Alternatively, you may need some kind of client that reads the data and then formats it for the platform that the viewer is using.

提交回复
热议问题