Search code examples
javafileio

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


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.");
    }
}
}

Solution

  • 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.