Difference between PrintWriter and FileWriter class

后端 未结 4 1635
灰色年华
灰色年华 2021-02-05 21:17
try{

    File file = new File(\"write.txt\");
    FileWriter writer = new FileWriter(file);

    PrintWriter printWriter = new PrintWriter(writer);
    printWriter.prin         


        
4条回答
  •  既然无缘
    2021-02-05 22:02

    From the source what PrintWriter does when you pass a File is to open it in a buffered way

    public PrintWriter(File file) throws FileNotFoundException {
        this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
             false);
    }
    

    if you pass it a FileWriter, it will open it, without buffering

    public FileWriter(File file) throws IOException {
        super(new FileOutputStream(file));
    }
    

    This means that the first example can be slightly more efficient. However I would use the File without the FileWriter because to me it is simpler.

提交回复
热议问题