0

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.

verified_tinker
  • 625
  • 5
  • 17

4 Answers4

0
String inputFilename = "coords.txt";

Where does this exist on your disk? Make sure your code points to the file location, I suspect at the moment it doesn't. You could try getting it relative to the classpath.

InputStream input = getClass().getResourceAsStream("coords.txt"); 
Squiggs.
  • 4,299
  • 6
  • 49
  • 89
  • At the moment, it is in the same directory as WriteCSV.java (the code above) is. And as I said, it works if the path is entered. However, the code is written for the grading program I mentioned, and as I do not know how that program works, I don' know the specific address and thus cannot specify the path. – verified_tinker Oct 30 '17 at 20:44
0

Relative paths (such as coords.txt) are resolved relative to the directory the program is run from, not where the source code resides.

Try printing:

System.out.println(new File("coords.txt").getAbsolutePath());

To see the absolute path the file is being resolved as. If you're running in an IDE this is often the directory of the project root, not the source directory - but you'll have to figure out where it's running from.


Also, prefer the Path APIs instead of File - Java 7 introduced Path and it's a much safer, more robust File I/O utility.

dimo414
  • 47,227
  • 18
  • 148
  • 244
  • The result of `.getAbsolutePath()` is the directory where the .java file is located: `D:\Semetre\Dropbox\Java Projects\Programming Assingments (Labs)\coords1.txt` (I changed it to coords1.txt in order to avoid any name conflict). – verified_tinker Oct 30 '17 at 21:02
  • There's no need to change the filename, `new File(String)` doesn't do anything to the filesystem, it just creates a `File` object. If that path correctly reflects the location of the `coords.txt` file then it's likely you were doing something else to munge the path that was being opened, but it's hard to say what. – dimo414 Oct 30 '17 at 21:54
-1

This has nothing to do with where your .java source file is. I think your question is answered here already https://stackoverflow.com/a/3844316/8843830.

Florian Wilhelm
  • 600
  • 4
  • 17
  • This may be by far the best answer, provided it works, and it would, I think, be satisfactory normally. As it is, this Java code is homework you're looking at, and we haven't yet covered `getClass().getResourceAsStream("ListStopWords.txt");` at all or, indeed, the InputStream class itself (beyond the theoretical and the superficial). – verified_tinker Oct 30 '17 at 20:53
-1

I kept messing around it, and it works in the grading program, now. The downside: I have no idea what's different. To me, the question can be considered closed, so feel free to post any solutions that come to mind, if you want to help posterity.

The new code:

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

public class WriteCSV {
    public static void main(String[] args) {

        //  Grading program needs hardcoded filename. Oh, well. "
        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 = 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;
    }
}
verified_tinker
  • 625
  • 5
  • 17
  • The only meaningful change between this code and the version in your question is the line `line.replace(' ', ',');` was changed to `line = line.replace(' ', ',');`, which would not be reached until after the file was successfully opened. My guess is you changed something on the file system (renamed or moved the files in question) to the location your code expected. – dimo414 Oct 30 '17 at 22:01