Scanner will take user input but will not find the file

北慕城南 提交于 2019-12-13 04:50:10

问题


This is a program to read a file and print out the file with some of the text edited. The code will compile the issue is that it will read the users input but will say file is not found when the file is there. I feel like I am missing something. I am brand new at this so go easy on me.


回答1:


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MainTest {

    public static void main(String args[]) {
      //  if (args[0] != null)
            readFile();
    }

    public static void readFile() { // Method to read file

        Scanner inFile = null;
        String out = "";
        try {
            Scanner input = new Scanner(System.in);
            System.out.println("enter file name");
            String filename = input.next();
            File in = new File(filename); // ask for the file name
            inFile = new Scanner(in);


            int count = 0;
            while (inFile.hasNextLine()) { // reads each line
                String line = inFile.nextLine();


                for (int i = 0; i < line.length(); i++) {
                    char ch = line.charAt(i);
                    out = out + ch;

                    if (ch == '{') {
                        count = count + 1;
                        out = out + " " + count;
                    } else if (ch == '}') {
                        out = out + " " + count;
                        if (count > 0) {
                            count = count - 1;
                        }
                    }
                }
            }
            System.out.println(out);
        } catch (FileNotFoundException exception) {
            System.out.println("File not found.");
        }
        inFile.close();
    }
}



回答2:


You can use System.getProperty("user.dir") to find where Scanner looking to find your file. And you should be sure your file is located here.



来源:https://stackoverflow.com/questions/19600409/scanner-will-take-user-input-but-will-not-find-the-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!