Java read from one file and write into another file using methods

Newbie picture Newbie · Feb 3, 2015 · Viewed 32.6k times · Source

I am learning Java and working on File IO and right now stuck in reading text from One file and write in another file. I am using two different methods first one for reading and displaying text in console from file #1 and using another method to write in file#2.

I can successfully read and display contents from File#1 but not sure how to write the text in file#2.

Here is the code which I have written so far:

import java.io.*;
public class ReadnWrite {
    public static void readFile() throws IOException {
        BufferedReader inputStream = new BufferedReader(new FileReader(
                "original.txt"));
        String count;
        while ((count = inputStream.readLine()) != null) {
            System.out.println(count);
        }
        inputStream.close();
    }
    public static void writeFile() throws IOException{
        BufferedWriter outputStream = new BufferedWriter(new FileWriter(
        "numbers.txt"));

//Not sure what comes here
    }
    public static void main(String[] args) throws IOException {
        checkFileExists();
        readFile();
    }
}

This is just for my own learning as there are lots of examples to read and write without using different methods but I want tolearn how I can achieve through different methods.

Any help will be highly appreciated.

Regards,

Answer

jnd picture jnd · Feb 3, 2015

You can write to another file using: outputStream.write(). And when you are done just outputStream.flush() and outputStream.close().

Edit:

public void readAndWriteFromfile() throws IOException {
    BufferedReader inputStream = new BufferedReader(new FileReader(
            "original.txt"));
     File UIFile = new File("numbers.txt");
        // if File doesnt exists, then create it
        if (!UIFile.exists()) {
            UIFile.createNewFile();
        }
    FileWriter filewriter = new FileWriter(UIFile.getAbsoluteFile());
    BufferedWriter outputStream= new BufferedWriter(filewriter);
    String count;
    while ((count = inputStream.readLine()) != null) {
        outputStream.write(count);
    }
    outputStream.flush();
    outputStream.close();
    inputStream.close();