【问题标题】:Java can't read a text fileJava 无法读取文本文件
【发布时间】:2017-01-30 20:57:39
【问题描述】:

我正在尝试读取一个 .txt 文件并搜索一个单词,但程序只是以 Process finished with exit code 0 关闭。

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

public class LogParser {
    static  Scanner file;
    static ArrayList text = new ArrayList();
    static String path = new String();
    static String check = new String();
    private static int a = 0;
    static  Scanner inpunt = new Scanner(System.in);


    public static void main (String[] args) {

        System.out.println("Input path to file");
        path = inpunt.nextLine();
        File texts = new File(path);

        try {
            file = new Scanner(new File(path)); 
        } catch (Exception e) {
            System.out.println("Can't open file");
        }

        try {
            while (file.hasNext()) {
                text.add(a, file.nextLine());
                check = text.get(a).toString();
                if (check.contains("cap"))
                    System.out.println("Allert!!!!!!!!!!!!!!!!!!!!!!!!!!!" + text.get(a));
                a = a + 1;

            }
        } catch (Exception e) {
           // System.out.println("Can't open file");
            if (file.toString().contains("cap"))
                System.out.println("cap" + "Path to file: " + path);
            System.out.println(text.size());
        }

    }

}

.txt 文件中的文字是:

let's try read this cap

如果我尝试打开一个 xml 文件,一切正常。我的问题只在 txt 文件中。

【问题讨论】:

  • 你能试着解释一下自己吗?
  • 不清楚path 的设置位置。请尝试以易于重现问题的方式修改您的代码。您遇到的错误/异常是什么?帮助我们帮助你...
  • 路径未设置。

标签: java parsing text


【解决方案1】:

如 cmets 中所述,您的路径变量未设置。您正在尝试创建一个新文件并传入一个尚未实例化的路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 2018-04-27
    • 2016-08-08
    相关资源
    最近更新 更多