Code:
import java.io.*;
import java.util.Scanner;
public class WriteCSV {
public static void main(String[] args) {
String inputFilename = "coords.txt";
String outputFilename = changeFileExtToCsv(inputFilename);
// Open files
PrintWriter output = openOutput(outputFilename);
Scanner input = openInput(inputFilename);
String line;
while (input.hasNextLine())
{
line = input.nextLine();
line.replace(' ', ',');
output.println(line);
}
input.close();
output.close();
}
/**
* Changes file extension to ".csv"
* @param filename
* @return new filename.extension
*/
public static String changeFileExtToCsv(String filename) {
return filename.substring(0,filename.lastIndexOf('.')) + ".csv";
}
/**
* Open input for reading
* @param filename
* @return a Scanner object
*/
public static Scanner openInput(String filename) {
Scanner in = null;
try {
File infile = new File(filename);
in = new Scanner(infile);
} catch (FileNotFoundException e) {
e.printStackTrace();
//System.out.println(filename + " could not be found");
System.exit(0);
}
return in;
}
/**
* Open output for writing
* @param filename
* @return a PrintWriter object
*/
public static PrintWriter openOutput(String filename) {
PrintWriter output = null;
try {
File outFile = new File(filename);
output = new PrintWriter(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
//System.out.println(filename + " could not be found");
System.exit(0);
}
return output;
}
}
Error message:
java.io.FileNotFoundException: coords.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at WriteCSV.openInput(WriteCSV.java:44)
at WriteCSV.main(WriteCSV.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Process finished with exit code 0
Line 44 is File infile = new File(filename);
and coords.txt (and .csv) are located in the same directory the .java file is in.
When giving a File object only the filename and its extension, should it not look for that file in the same directory the .java file is located?
When the whole path is entered, the program works fine (so long as the coords.txt file exists there).
Moreover, when submitted to a grading program (how it works is hidden from me), it gives this: "Program timed out". And I'm not sure what that means.