4

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

// 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);
}

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

4

5 回答 5

5

- 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, Files deal with bytes, and Buffer deals with characters, so there is a conversion of bytes to characters and trust me it works well, there will not be any noticeable overhead.

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 Scanner there is no need to use BufferedReader

于 2012-11-01T09:08:11.713 回答
3

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

    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();
    }

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

    try (
            Reader r = new FileReader("test.txt");
            Scanner s = new Scanner(r)
            ) {
        // Do your stuff here.
    }
于 2012-11-01T11:27:51.307 回答
2

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

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")
于 2012-11-01T08:27:57.617 回答
2

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

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

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

   while(s.hasNext()){

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

    s.next();
    }
     s.close();
于 2012-11-01T08:31:57.543 回答
0

我通常这样做:

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)));
于 2017-06-30T19:01:40.997 回答