简体   繁体   中英

Java Method Can't Pick Up Files

I'm writing a Java program that has a working drag and drop GUI for files. All of the files that are dragged in the DnD GUI are put into an String array that holds the file names. I have a method that loops through the array and strips the path to leave only the filenames and then sends the filename (for the Scanner) and the desired output filename (for the PrintWriter) to this method at the end of each loop:

public void fileGenerator(String in, String out) {          
    try {
    String current_directory = System.getProperty("user.dir");
    Scanner input = new Scanner(new FileReader(current_directory+"/"+in));
    PrintWriter output = new PrintWriter(current_directory+"/"+out);
        while(input.hasNext()) {
            String line = input.nextLine();
            output.println(line);
        } output.close(); 
    input.close();
    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }
}

The code is not working, it does not produce the output file. I am getting a "No such file or directory" error with the full path... I have tested it in terminal, it is the correct path. Any input is appreciated.

I should note that all of the Java source files, classes, and input files are in the same directory.

Thanks!

First problem I see is that you ignore the exception, so you don't know if it opens the input file successfully. Don't ignore exceptions, even if you don't know what to do with them, print them so you could analyze your problems later on.

Second, debug the code, see where it gets an exception, if at all, see what are the values at each step.

Third, to answer your question, assuming you work with Eclipse, if you refer to the file with relative path, the working directory is not the source / class folder, but the project folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM