0

这是一个读取文件并打印出文件并编辑了一些文本的程序。代码将编译问题是它会读取用户输入,但当文件存在时会说文件未找到。我觉得我错过了什么。我在这方面是全新的,所以请放轻松。

4

2 回答 2

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();
    }
}
于 2013-10-25T22:48:22.103 回答
0

您可以使用System.getProperty("user.dir")来查找Scanner查找文件的位置。您应该确保您的文件位于此处。

于 2013-10-25T22:47:24.300 回答