首页 > 解决方案 > 在 Java 中读取 .txt 文件

问题描述

我正在尝试编写一个程序,该程序读取在网络中相互交互的节点列表。这以以下格式写入文本文件:

node1   node2
node1   node3
node2   node3
node3   node5

这表明 node1 与 node2 和 node3 交互,node 2 仅与 node3 交互等。

如果我输入节点的名称,该程序将能够读取此文件并删除任何重复的交互,并将能够向我返回节点与其他节点的交互次数。但是,我对 Java 很陌生,我首先尝试让它读入文件,尽管我的代码目前没有读入文件。这是我到目前为止的代码:

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

public class ReadFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("interactions.txt");
      Scanner FileReader = new Scanner(myObj);
      while (FileReader.hasNextLine()) {
        String data = FileReader.nextLine();
        System.out.println(data);
      }
      FileReader.close();
    } 
  }
}

任何有关如何解决此问题的帮助将不胜感激,谢谢!

标签: javafile

解决方案


这可能是因为文件在您正在查找的位置不存在。您可能错过了 catch 子句,您可以在其中打印确切的异常。

首先,尝试运行这个:

public static void main(String[] args) throws IOException {
    try {
        File myObj = new File("interactions.txt");
        Scanner FileReader = new Scanner(myObj);
        while (FileReader.hasNextLine()) {
            String data = FileReader.nextLine();
            System.out.println(data);
        }
        FileReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

文件应该位于项目的根级别,这也可能对您有所帮助

public static void main(String[] args) throws IOException {
    try {
        File myObj = new File("interactions.txt");

        // check if file exists - if not - create
        if (myObj.createNewFile()) {
            System.out.println("File created: " + myObj.getName());
        } else {
            System.out.println("File already exists.");
        }
        Scanner FileReader = new Scanner(myObj);
        while (FileReader.hasNextLine()) {
            String data = FileReader.nextLine();
            System.out.println(data);
        }
        FileReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

推荐阅读