gpt4 book ai didi

java - java中从文件输入

转载 作者:行者123 更新时间:2023-11-30 03:17:06 24 4
gpt4 key购买 nike

我是java初学者,我正在尝试将数据输出到我称之为a.txt的文件中。需要帮助,我不知道我收到异常错误文件未打开。我将 a.txt 放在与 main 和 readfile 相同的目录中。

- main path : C:\Users\Navdeep\Desktop\java\assign1\src\assign1

- readfile : C:\Users\Navdeep\Desktop\java\assign1\src\assign1

- a.txt : C:\Users\Navdeep\Desktop\java\assign1\src\assign1

提前致谢。

main.java

package assign1;

public class main {
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
}
<小时/>

readile.java

package assign1;

import java.io.*;
import java.util.*;

public class readfile {
private Scanner x;

public void openFile() {
try {
x = new Scanner(new File("a.txt"));
} catch (Exception e) {
System.out.println("file not open \n");
}
}

public void readFile() {
while (x.hasNext()) {
String Agent = x.next();
String request_type = x.next();
String classtype = x.next();
String numberofseat = x.next();
String arrivaltime = x.next();

System.out.printf("%s %s %s %s %s \n", Agent,
request_type, classtype, numberofseat, arrivaltime);
}
}
public void closeFile() {
x.close();
}
}
<小时/>

a.txt

1 r e 1 0
2 r e 1 1

最佳答案

如果您使用带有相对路径的文件,则假定它相对于“当前用户目录”。什么是“当前用户目录”?请参阅文档:

A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

同样来自文档:

On UNIX systems, a relative pathname is made absolute by resolving it against the current user directory. On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.

因此,使用相对路径找到文件的一种方法是在包含该文件的目录中启动 JVM。

但是,这种方法可能有一定的限制,因为它限制您始终在某个目录中启动 JVM。

作为替代方案,您可以考虑使用ClassLoader#getResourceAsStream。这允许您加载 JVM“类路径”上的任何资源。类路径可以通过多种不同的方式进行配置,包括在启动时使用 JVM 的参数。因此,我建议使用它,而不是使用 File 初始化您的 Scanner。这看起来像:

InputStream is = StackOverflow.class.getClassLoader().getResourceAsStream("a.txt");
Scanner scanner = new Scanner(is);

现在,当使用getResourceAsStream时,您必须确保引用的文件位于classpath上保存您的程序的 Java 虚拟机进程的名称。

您在评论中说过您正在使用 Eclipse。

在 Eclipse 中,您可以通过执行以下操作来设置执行的类路径:

1) 运行程序至少一次后,单击错误或播放标志旁边的小下拉箭头。

2) 单击“调试配置”或“运行配置”。

3) 在左侧边栏中,选择以您正在运行的程序命名的运行配置

4)单击“类路径”选项卡

5) 点击“用户条目”

6) 点击“高级”

7) 选择“添加文件夹”

8) 选择a.txt所在的文件夹。

完成此操作后,您可以使用刚刚设置的运行配置来运行程序,并且会找到a.txt。

类路径的基本思想

类路径代表程序运行时 JVM(Java 虚拟机)所知道的资源。如果您熟悉命令行工作,您可以将其视为类似于操作系统的“PATH”环境变量。

您可以深入阅读here .

关于java - java中从文件输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32302642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com