Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File I/O: Reading from one file and writing to another (Java)

Tags:

java

file

io

I'm currently working on a lab in my cpe class and we have to create a simple program that scans in strings from a .txt file and prints them to a different .txt file. So far I have the basic program drawn out but my exception keeps getting throw though I have all the necessary files. Can anyone help me debug?

import java.io.*;
import java.util.*;

public class FileIO {

public static void main(String args[]) {        
    try {
        File input = new File("input");
        File output = new File("output");
        Scanner sc = new Scanner(input);
        PrintWriter printer = new PrintWriter(output);
        while(sc.hasNextLine()) {
            String s = sc.nextLine();
            printer.write(s);
        }
    }
    catch(FileNotFoundException e) {
        System.err.println("File not found. Please scan in new file.");
    }
}
}
like image 993
Mike Avatar asked May 14 '12 17:05

Mike


People also ask

How can you open a file for both reading and writing in Java?

You can't open the same file to read and write at the same time. You have to open and save the file information in a data structure and then close it. Then you have to work with the data structure in memory and open the file to write results.


2 Answers

You need to figure out where it looks for the "input" file. When you just specify "input" it looks for the file in the current working directory. When working with an IDE, this directory may not be what you think it is.

Try the following:

System.out.println(new File("input").getAbsolutePath());

to see where it looks for the file.

like image 56
aioobe Avatar answered Oct 15 '22 05:10

aioobe


May be you are just forget the flush()

       try {
            File input = new File("input");
            File output = new File("output");
            Scanner sc = new Scanner(input);
            PrintWriter printer = new PrintWriter(output);
            while (sc.hasNextLine()) {
                String s = sc.nextLine();
                printer.write(s);
            }
            **printer.flush();**
        }
        catch (FileNotFoundException e) {
            System.err.println("File not found. Please scan in new file.");
        }
like image 27
isvforall Avatar answered Oct 15 '22 05:10

isvforall