Java 文件 I/O 的良好实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13173369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:45:51  来源:igfitidea点击:

Good practice in Java File I/O

javafile-iofilewriterprintwriterbufferedwriter

提问by Happy Mittal

I am trying to read integers from a file, apply some operation on them and writing those resulting integers to another file.

我试图从文件中读取整数,对它们应用一些操作并将这些结果整数写入另一个文件。

// Input
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
Scanner s = new Scanner(br);

// Output
FileWriter fw = new FileWriter("out.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);

int i;

while(s.hasNextInt())
{
    i = s.nextInt();
    pw.println(i+5);
}

I want to ask is it a good practice to wrap these input and output streams like this?
I am new to java and on internet, I saw lots of other ways of I/O in files. I want to stick to one approach so is above the best approach ?

我想问一下,像这样包装这些输入和输出流是一个好习惯吗?
我是 Java 和互联网的新手,我在文件中看到了很多其他的 I/O 方式。我想坚持一种方法,所以是最好的方法吗?

回答by Kumar Vivek Mitra

-Well consider that you went shopping into a food mall, Now what you do usually, pick-up each item from the selves and then go to the billing counter then again go to the selves and back to billing counter ....?? Or Store all the item into a Cart then go to the billing counter.

-想想你去食品商场购物,现在你通常做的事情是,从自己那里拿起每件物品,然后去计费柜台,然后再去自己,然后回到计费柜台......??或将所有物品放入购物车,然后前往计费柜台。

-Its similar here in Java, Filesdeal with bytes, and Bufferdeals with characters, so there is a conversion of bytes to characters and trust me it works well, there will not be any noticeable overhead.

-它在 Java 中类似,Files处理字节和Buffer处理字符,因此将字节转换为字符,相信我它运行良好,不会有任何明显的开销。

So to Read the File:

所以要读取文件:

File f = new File("Path");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);

So to Write the File:

所以要写文件:

File f = new File("Path");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);

And when you use Scannerthere is no need to use BufferedReader

当你使用时Scanner,不需要使用BufferedReader

回答by manfcas

Keep in mind that the design of those classes is based on the Decorator design pattern. A good practice is to close all instances of java.io.Closeablein a finallyblock. For example:

请记住,这些类的设计基于装饰器设计模式。一个好的做法是关闭的所有实例java.io.Closeablefinally块。例如:

    Reader r = null;
    Scanner s = null;
    try {
        r = new FileReader("test.txt");
        s = new Scanner(r);
        // Do your stuff here.
    } finally {
        if (r != null)
            r.close();
        if (s != null)
            s.close();
    }

or, if you are using Java 7 or higher:

或者,如果您使用的是 Java 7 或更高版本:

    try (
            Reader r = new FileReader("test.txt");
            Scanner s = new Scanner(r)
            ) {
        // Do your stuff here.
    }

回答by clinton

Scanner does not need the BufferedReader. You can wrap it over the FileReader.

Scanner 不需要 BufferedReader。您可以将它包装在 FileReader 上。

Scanner s = new Scanner(new FileReader("test.txt"));

While using the scanner its better to assume that the source contains various content. Its good to close the scanner after using it.

在使用扫描仪时,最好假设来源包含各种内容。用完后关闭扫描仪就好了。

   while(s.hasNext()){

    if(s.hasNextInt())
      int i = s.nextInt();

    s.next();
    }
     s.close();

回答by PermGenError

you dont really need BuffredWriterwhen you are using PrintWriterto write character data, printwriterhas a constructor which takes filewriteras an argument. and dont need a scannerto readfrom a fileyou could acheive it using bufferedreaderitself.

BuffredWriter当你PrintWriter用来写字符数据时,你真的不需要,printwriter有一个构造函数,它filewriter作为一个argument. 并且不需要一个scannerto readfrom afile你可以使用bufferedreader它自己来实现它。

FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
while((line=br.readLine())!=null){
//do read operations here
}

FileWriter fw = new FileWriter("out.txt");
PrintWriter pw = new PrintWriter(fw);
 pw.println("write some data to the file")

回答by Angel

I usually do this:

我通常这样做:

String inputFileLocation = "Write it here";

BufferedReader br = new BufferedReader(new FileReader(new File(fileLocation)));

while((line=br.readLine())!=null){
//Scanner operations here
}

String outputFileLocation = "Here";
PrintWriter pr = new PrintWriter(new FileWriter(new File(outputFileLocation)));