BufferedReader / BufferedWriter逐行输出

时间:2012-03-01 13:45:54

标签: java bufferedreader bufferedwriter

我有以下问题:我需要输入一个包含12行的文件。每行包含8个字符。我必须在一个包含8行和12个字符的文件中输出它。我必须逐行读取输入并同时输出每一行。所以我不允许先读取我的输入,在我读完之后只需要输入8行,每行12个字符。我正在使用BufferedReader来读取我的文件,使用BufferedWriter来写入我的文件。所以举个例子:

输入:
12345678个
qwertyui
asdfghjk

输出:
12345678qwer
tyuiasdfghjk

编辑:这确实是一项家庭作业。

BufferedWriter bufferedWriter = null;
    FileReader fr;

    try {
        fr = new FileReader(new File(directory to file));
        bufferedWriter = new BufferedWriter(new FileWriter(directory to file);

        BufferedReader br = new BufferedReader(fr);
        String line = br.readLine();

        while (line != null) {

            bufferedWriter.write(output);

            bufferedWriter.newLine();

            line = br.readLine();
        }

        br.close();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        //Close the BufferedWriter
        try {
            if (bufferedWriter != null) {
                bufferedWriter.flush();
                bufferedWriter.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

这是我读取输入文件并写入输出文件的方式,这是我目前的代码。

2 个答案:

答案 0 :(得分:6)

使用read类的Reader方法。 (FileReaderReader)的后代。 我不会实现整个逻辑,但这是一个可以工作的骨架。

FileReader inputStream = null;
FileWriter outputStream = null;

try {
    inputStream =
        new FileReader("inputfile.txt");
    outputStream =
        new FileWriter("outputfile.txt");

    int c;
    int counter = 1;
    while ((c = inputStream.read()) != -1) {
        //keep a counter that will cycle for 12 characters
        //check if c represents a alphabet or number, write it to file else skip 
        //when counter is 12 write a newline
        outputStream.write(c);
    }
} finally {
    if (inputStream != null) {
        inputStream.close();
    }
    if (outputStream != null) {
        outputStream.close();
    }
}

答案 1 :(得分:0)

read方法允许您控制要读取的字符数:

请参阅BufferedReader#read

write

相同