【问题标题】:JavaFX Reading from file throws "InvocationTargetException"?JavaFX 从文件中读取抛出“InvocationTargetException”?
【发布时间】:2016-04-01 09:08:05
【问题描述】:

我一直试图了解问题的确切原因,但无论我做什么似乎都不起作用。 我有一个文本文件,其中列出了名称和数字,用冒号分隔。 一个例子是:

贝蒂·罗斯:52

安吉·斯科茨:29

迈克尔·罗森:72

列表很长,超过 10,000 行。

public class PeopleIds {
    public static int UNDEFINED_ID = -1;
    private static HashMap<String, Integer> people;

    public static void initialize() {
        people = new HashMap<String, Integer>();
        System.out.println(new File("res/ids/people_ids.txt").exists());
        try {
            Files.lines(Paths.get("res/ids/people_ids.txt")).forEach(s -> {
                people.put(s.replaceAll(":.*", "").trim(), Integer.parseInt(s.replaceAll(".*:", "")));
            });
        } catch (IOException e) {
            System.out.println("Unable to read specified file.");
            e.printStackTrace();
        }
    }

    public static int getId(final String name) {
        final Integer id = people.get(name);
        return id != null ? id : UNDEFINED_ID;
    }
}

我从GUIController 类调用initialize 方法:

public class GUIController implements Initializable {
    @FXML
    private TableView<PersonData> personTable;
    @FXML
    private TableColumn<PersonData, String> name;
    @FXML
    private TableColumn<PersonData, Integer> limit;
    @FXML
    private TextField searchInput;
    @FXML
    private ImageView personIcon;

    private Image undefinedIcon;
    private PersonIcon icon;
    private ObservableList<PersonData> data;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        PeopleIds.initialize();
        undefinedIcon = new Image(getClass().getResourceAsStream("/ids/no.png"));
        name.setCellValueFactory(new PropertyValueFactory<PersonData, String>("name"));
        limit.setCellValueFactory(new PropertyValueFactory<PersonData, Integer>("limit"));
        data = PriceData.getData();
        personTable.setPeople(data);
        searchInput.textProperty().addListener((ov, oldValue, newValue) -> {
            final String input = searchInput.getText();
            if (input.length() == 0) return;
            searchInput.setText(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
            filterSearch();
        });
    }
}

当我用PeopleIds.initialize()从这个类中调用它时,抛出了一个异常,告诉我应用程序启动方法中有一个异常。

这是完整记录的内容:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$156(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: javafx.fxml.LoadException: 
/C:/Confidential/bin/base/PersonGUI.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
    at javafx.fxml.FXMLLoader.load(Unknown Source)
    at base.PersonGUI.start(PersonGUI.java:13)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$163(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$null$174(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$149(Unknown Source)
    ... 1 more
Caused by: java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
    at java.io.BufferedReader$1.hasNext(Unknown Source)
    at java.util.Iterator.forEachRemaining(Unknown Source)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
    at java.util.stream.ReferencePipeline$Head.forEach(Unknown Source)
    at base.PeopleIds.initialize(PeopleIds.java:17)
    at base.GUIController.initialize(GUIController.java:36)
    ... 18 more
Caused by: java.nio.charset.MalformedInputException: Input length = 1
    at java.nio.charset.CoderResult.throwException(Unknown Source)
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
    at sun.nio.cs.StreamDecoder.read(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    ... 24 more
Exception running application base.PersonGUI

我不确定这里发生了什么?我已经调查过了,人们说要移动 fxml 文件(用于格式化内容并与 GUIController 链接到与 Main 类相同的包,但它已经是。

我几天来一直在努力解决这个问题,但无济于事。你们中的任何人都有过这个问题的经验吗?如果是这样,您是如何解决的?非常感谢。

【问题讨论】:

  • 你试过调试吗?异常真的来自PeopleIds.initialize(); 还是来自你的变量在下面的行中为空?

标签: java file exception javafx


【解决方案1】:

如果在读取文件时有Exception,而不是在打开文件时,则会为Files.lines 流操作抛出未经检查的异常Stream.forEach 没有throws 子句)。

这发生在这里

Files.lines(Paths.get("res/ids/people_ids.txt")).forEach(s -> {
    people.put(s.replaceAll(":.*", "").trim(), Integer.parseInt(s.replaceAll(".*:", "")));
});

,您可以在堆栈跟踪中轻松看到:

Caused by: java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1

(这是由于使用了错误的Charset,请参阅Files.readAllBytes vs Files.lines getting MalformedInputException

catch 子句不会捕获这种异常:

} catch (IOException e) {

你需要使用

} catch (Exception e) {

也捕获未经检查的异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-11
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多