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.");
}
}
}
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.
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.
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.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With