简体   繁体   中英

BufferedReader/BufferedWriter Output line by line

I have the following problem: I need to input a file with 12 lines. Each line consist of 8 characters. I have to output it in a file with 8 lines and 12 characters. I have to read the input line by line and output each line at the same time. So I'm not allowed to read my input first and after i read it just cut in in 8 lines with 12 characters. I'm using BufferedReader to read my file and BufferedWriter to write to my file. So by example:

Input:
12345678
qwertyui
asdfghjk

Output:
12345678qwer
tyuiasdfghjk

Edit: It's an homework assignment indeed.

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

This is how i read my inputfile and write to an outputfile, and it's the code I have at the moment.

Use the read method of Reader class. ( FileReader is a descendant of Reader ). I'm not going to implement the whole logic but here is a skeleton to work on.

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

The read method allows you to control how many characters to read:

See BufferedReader#read .

Same with write

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM