4

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,

Newbie
  • 103
  • 2
  • 3
  • 13
  • You want to read from original.txt and write everything to numbers.txt? – jnd Feb 03 '15 at 03:55
  • 1
    possible duplicate of [How to Write text file Java](http://stackoverflow.com/questions/15754523/how-to-write-text-file-java) – void Feb 03 '15 at 03:56
  • O comon man, use your common sense. The link is using the code written inside Main method. I can easily achieve that thing but I want to use two different methods without using Reader object in write method. – Newbie Feb 03 '15 at 04:11
  • #Farhang Amary, kindly read through the question properly before posting any possible duplicate question. I have gone through the link and that is using writing to a file in Main() and also I do not want to write any stupid "HELLO WORLD" text by myself. I want to write whatever I am reading from file#1 (original.txt) and write it into file#2(numbers.txt). – Newbie Feb 03 '15 at 04:24

3 Answers3

5

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();
jnd
  • 754
  • 9
  • 20
  • Thanks #jnd but if I try by just giving outputStream.write(); java gives me error that Missing argument to match .write( ) and also how does java know that what I want to save in the file. I believe I have to put all the text from original.txt file in to an object or an array and then write the contents of array/ object in outputStream.write(); in order to write in numbers.txt file. – Newbie Feb 03 '15 at 04:09
  • You put what you want to write as the arguement. For example `outputStream.write("hello");` or `outputStream.write(15);` – jnd Feb 03 '15 at 04:10
  • #jnd I think you didn't get my question as I am retrieving text from file#1 and writing in file#2. Its not that I want to write anything from myself inside quotes... – Newbie Feb 03 '15 at 04:15
  • Thanks #jnd for the reply. It is almost similar to what I wanted. I have achieved my desired my results through your code but can I ask you a question that e.g. If my program asks the user to press 1 to read from file and 2 to write to a new file and do I have to use this BufferedReader method and read the file if user press 2 or is there a way that if user has pressed 1 and the program has saved all the file contents in an array/ arraylist and when user has pressed 2 it writes everything from that array/arraylist into file#2. – Newbie Feb 03 '15 at 04:35
  • You can do either way. You would just make your read method return an array of strings and then pass that to your write method for it to write. – jnd Feb 03 '15 at 04:38
  • No need to call outputStream.flush(); .. it will be called implicitly by outputStream.close(); – Maher Abuthraa Feb 14 '17 at 17:13
1

I'd use a BufferedReader that wraps a FileReader and a BufferedWriter that wraps a FileWriter.

Since you want to do it using two different methods you have to store the data in a List<String> data to pass it between the methods.

public class ReadnWrite {

    public static List<String> readFile() throws IOException {
        try(BufferedReader br = new BufferedReader(new FileReader("original.txt"))){
            List<String> listOfData = new ArrayList<>();
            String d;
            while((d = br.readLine()) != null){
                listOfData.add(d);
            }
            return listOfData;
        }
    }

    public static void writeFile(List<String> listOfData) throws IOException{
        try(BufferedWriter bw = new BufferedWriter(new FileWriter("numbers.txt"))){
            for(String str: listOfData){
                bw.write(str);
                bw.newLine();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        List<String> data = readFile();
        writeFile(data);
    }
}

As an alternative, if you don't have to do operations on the data between read and write I'd also do it in one method.

public class CopyFileBufferedRW {

    public static void main(String[] args) {
        File originalFile = new File("original.txt");
        File newFile = new File(originalFile.getParent(), "numbers.txt");

        try (BufferedReader br = new BufferedReader(new FileReader(originalFile));
             BufferedWriter bw = new BufferedWriter(new FileWriter(newFile))) {
            String s;
            while ((s = br.readLine()) != null) {
                bw.write(s);
                bw.newLine();
            }
        } catch (IOException e) {
            System.err.println("error during copying: " + e.getMessage());
        }
    }
}
xtra
  • 1,957
  • 4
  • 22
  • 40
0

Here is my way how to copy files:

BufferedReader br = null;
BufferedWriter bw = null;

try {
    br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("origin.txt"))));
    bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("target.txt"))));

    int i;
    do {
        i = br.read();
        if (i != -1) {
            bw.write(i);
        }
    } while (i != -1);

} catch (IOException e) {
    System.err.println("error during copying: "+ e.getMessage());
} finally {
    try {
        if (br != null) br.close();
        if (bw != null) bw.close();
    } catch (IOException e) {
        System.err.println("error during closing: "+ e.getMessage());
    }
}
Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103