为什么要使用PrintWriter而不是其他Writer

以一段代码,来说明这个主题。

public class BasicFileOutput {

    static String fromFile = "d:/struts-default.xml";

    static String toFile = "d:/setup.log";

    public static void main(String[] args) throws IOException {

         BufferedReader in = new BufferedReader(

        new StringReader(BufferedInputFile.read(fromFile)));

        int lineCount = 1;

        String s;

        // using PrintWriter

        PrintWriter out = new PrintWriter(

        new BufferedWriter(new FileWriter(toFile)));

        while((s = in.readLine()) != null) {

            String content = new String(s.getBytes(), Charset.forName("UTF-8"));

            out.println(lineCount++ + ": " + content);

        }

         out.close();

    }

}

以上代码的输出结果显示,虽然我们并没有在输出中置入任何换行符,但是在PrintWriter向文件中写内容时,内容被自动换行了。查看Java api文档中对PrintWriter的描述,有一句话是这样的:These methods use the platform's own notion of line separator rather than the newline character. 可见,这个类在输出格式方面被刻意地处理过了。所以,如果我们需要向其他文件中writer有格式要求的字符流时,比如换行,用PrintWriter的println就很方便了。

你可能感兴趣的:(java,PrintWriter,Writer,JavaI/O操作)