java - 在 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();
}
}
}
任何有关如何解决此问题的帮助将不胜感激,谢谢!
解决方案
这可能是因为文件在您正在查找的位置不存在。您可能错过了 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();
}
}
推荐阅读
- amazon-web-services - Object construction with JMESpath
- lisp - GISC 练习 11.22d:为什么这是有状态的?
- apache-kafka - Confluent.Kafka Consumer Schema Registry 工件查找错误
- android - 如何在 WSL2/React Native 项目环境中设置 Flipper?
- java - 如何在 Android stuido 中添加硒?
- bin - 带方括号的 Bin 函数
- laravel - Laravel - 将 PDF 保存到 BLOB 中,导致作业序列化问题
- java - 为什么`Regex` 在 src/test 和 src/androidTest 有不同的行为?
- reactjs - 是否可以从全局自定义挂钩更新 React Context?
- amazon-web-services - 具有 IAM 凭证的跨账户 AWS Lambda