Java读写文件 - BufferedReader BufferedWriter

4
这是一段代码片段,基本上我想做的是从名为'listings.txt'的文件中读取并写入名为'overview.txt'的文件。 我想将'listings.txt'中的信息原样放入'overview.txt'中(稍后我会解决其余问题)。
文件'overview.txt'已创建并似乎循环遍历文件'listings.txt'并写入'overview.txt'。 但是,一旦我打开文件'overview.txt',它就是空的。
有人能快速浏览我的代码并发现错误吗?
package yesOverview;

import java.io.BufferedReader;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;


public class yesOverview {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String strInput = "foo.bar";
        System.out.print("Please enter the listings file (the full path to the file): ");
        strInput = input.next();

        //This makes sure that the inputed file is listings.txt as required for KET1 task 2
        while (strInput.contains("listings.txt") == false) {
            System.out.print("Incorrect file. Please enter listings file(the full path to the file): ");
            strInput = input.next();
        }

        infos(strInput);
        input.close();
    }

    public static void infos(String strInput) {
        Scanner input2 = new Scanner(System.in);
        System.out.print("Please enter the overview.txt file (the full path to the file): ");
        String strInput2 = "foo.bar";
        strInput2 = input2.next();

        //This also makes sure that the overview.txt file is provided. 
        while (strInput2.contains("overview.txt") == false) {
            System.out.print("Incorrect file. Please enter overview file(the full path to the file): ");
            strInput2 = input2.next();
        }

        //Creates the file f then places it in the specified directory.
        File f = new File(strInput2);

        try {
            //Creates a printerwriter out that writes to the output file. 
            PrintWriter out = new PrintWriter(strInput2);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(KETTask2Overview.class.getName()).log(Level.SEVERE, null, ex);
        }

        //String that holds the value of the next line. 
        String inputLine = "";

        //Creates the Buffered file reader / writer.  
        try {
            BufferedReader in = new BufferedReader(new FileReader(strInput));
            FileWriter fstream = new FileWriter(strInput2);
            BufferedWriter out = new BufferedWriter(fstream);
            while (in.readLine() != null) {
                out.write(in.read());
            }
            in.close();
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }

    }
}

6
你从未结束。 - bmargulies
2
@bmargulies是正确的 - 你必须关闭。最佳实践是将关闭调用放在finally { }块中。 - user949300
@user949300 或者在Java 7中使用try-with-resources语句。 - Jeffrey
你们说得对。非常感谢。我加上了out.close(),现在它可以工作了。虽然不是完美的,但我可以从这里弄清楚剩下的部分...谢谢!当我学习时,我会回报社区的! - RedHatcc
3个回答

9

试试这个

关闭BufferedWriter流(即out.close())

尝试使用nextLine()而不是next(),因为next()只能输入一个单词,但是要输入完整的一行,请使用nextLine(),尽管这似乎不是问题所在。

当我需要读写文件时,通常会按照以下步骤进行:

读取文件

File f = new File("my.txt");
FileReader fr = new FileReader(f);
BufferedReader br  = new BufferedReader(fr);

String s = null;

while ((br.readLine())!=null) {

// Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc

}

br.close();

写入文件:

Boolean isDone = true;
Scanner scan = new Scanner(System.in);
File f = new File("my.txt");
FileWriter fr = new FileWriter(f);
BufferedWriter br  = new BufferedWriter(fr);

while (isDone) {

   if (!isDone) {

 br.write(new Scanner(System.in).nextLine());

 }


}

整个问题在于我没有关闭它,虽然你提供的代码也非常有用。谢谢你的帮助! - RedHatcc
2
你怎么才能跳出 while (b) 循环,为什么在循环内部测试 !b,当 b 在其中永远不可能为 false 时?这毫无意义。 - user207421
这行代码必要吗? Scanner scan = new Scanner(System.in); - Nick Louloudakis
b 从未被定义。 - YisraelU

4
public static long copy (Reader input, Writer output) throws IOException {

    char[] buffer = new char[8192];
    long count = 0;
    int n;
    while ((n = input.read( buffer )) != -1) {
        output.write( buffer, 0, n );
        count += n;
    }
    return count;
}

使用示例:

 copy( reader, new FileWriter( file ) );

1

你没有关闭。 writeList方法的finally块清理并关闭BufferedWriter。

finally {
    if (out != null) { 
        System.out.println("Closing BufferedWriter");
        out.close(); 
    } else { 
        System.out.println("BufferedWriter not open");
    } 
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接