如何将文本文件加载到此程序中?

时间:2015-02-19 20:04:18

标签: java input

如何将文本文件加载到我在下面发布的java程序中。我试过但运气不好,任何帮助都将不胜感激!

谢谢。

  import java.io.*;


    public class test1 {
        public static void main(String args[]) throws Exception {
            if (args.length != 1) {
                System.out.println("usage: Tut16_ReadText filename");
                System.exit(0);
            }
            try {
                FileReader infile = new FileReader(args[0]);
                BufferedReader inbuf = new BufferedReader(infile);
                String str;
                int totalwords = 0, totalchar = 0;
                while ((str = inbuf.readLine()) != null) {
                    String words[] = str.split(" ");
                    totalwords += words.length;
                    for (int j = 0; j < words.length; j++) {
                        totalchar += words[j].length();
                    }
                }

                double density = (1.0 * totalchar) / totalwords;
                if (totalchar > 0) {
                    System.out.print(args[0] + " : " + density + " : ");
                    if (density > 6.0) 
                        System.out.println("heavy");
                    else
                        System.out.println("light");
                } else
                    System.out.println("This is an error - denisty of zero.");
                infile.close();
            } catch (Exception ee) {
                System.out.println("This is an error - execution caught.");
            }
        }
    }

3 个答案:

答案 0 :(得分:0)

首先,有一种更简单的方法来读取文件。从Java 7开始,FilesPaths类可以像这样使用:

public static void main(String[] args) throws IOException {

    if (args.length != 1) {
        System.out.println("usage: Tut16_ReadText filename");
        System.exit(0);
    }

    final List<String> lines = Files.readAllLines(Paths.get(args[0]));

    for (String line : lines) {
        // Do stuff...
    }

    // More stuff

}

然后,为了启动程序并让它读取您指定的文件,您必须在启动应用程序时提供参数。您可以在命令提示符后面的类名后传递该参数,如下所示:

  

$ java Tut16_ReadText /some/path/someFile.txt

这传递&#34; /some/path/someFile.txt"程序然后程序将尝试读取该文件。

答案 1 :(得分:0)

如果你正在运行java 8,那么使用新的io流是轻而易举的。优点是在大文件上,所有文本都不会被读入内存。

public void ReadFile(String filePath){

    File txtFile = new File(filePath);

    if (txtFile.exists()) {

        System.out.println("reading file");

        try (Stream<String> filtered = Files.
                lines(txtFile.toPath()).
                filter(s -> s.contains("2006]"))) {//you can leave this out, but is handy to do some pre filtering

            filtered.forEach(s -> handleLine(s));
                        }
    } else {
        System.out.println("file not found");
    }
}

private void handleLine(String lineText) {

    System.out.println(lineText);

}

答案 2 :(得分:0)

另一种方法是使用Scanner

Scanner s = new Scanner(new File(args[0]));
while(s.hasNext()){..}
相关问题