在Java中从src文件夹打开文本文件时出错

发布于 2024-11-30 03:30:36 字数 408 浏览 0 评论 0原文

我正在制作一个 Java 程序,想要打开一个 text(notepad) 文件,该文件已保存在我的 Java 程序的 src 文件夹中,我尝试通过下面的代码,但它给出了错误。 “Runtime 类型中的方法 exec(String) 不适用于参数 (InputStream),有什么建议吗?谢谢

Runtime runtime = Runtime.getRuntime();
InputStream lic = this.getClass().getClassLoader().getResourceAsStream("MyFile.txt");
Process process = runtime.exec(lic);

I am making a Java program and want to open a text(notepad) file ,that i have saved in src folder in my Java Program, I have tried to do it by the following code , but it is giving error. "The method exec(String) in the type Runtime is not applicable for the arguments
(InputStream) , Any suggestions ? Thanks

Runtime runtime = Runtime.getRuntime();
InputStream lic = this.getClass().getClassLoader().getResourceAsStream("MyFile.txt");
Process process = runtime.exec(lic);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

云仙小弟 2024-12-07 03:30:36

您无法执行输入流,它只是字节的集合,而不是文件。

您应该将此文件存储在项目内的其他位置(例如资源文件夹)并使用该路径打开该文件。它看起来是这样的:

File file = new File("resources/my-file.txt");
String[] command = { "notepad.exe", file.getAbsolutePath() };
Runtime.getRuntime().exec( command );

You can not execute an input-stream, it's just a collection of bytes, not a file.

You should store this file somewhere else inside your project (like a resources folder) and use the path to open the file. Here's how it would look like:

File file = new File("resources/my-file.txt");
String[] command = { "notepad.exe", file.getAbsolutePath() };
Runtime.getRuntime().exec( command );
冰火雁神 2024-12-07 03:30:36

所有 Runtime.exec 方法均不接受 InputStream

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html


InputStream 读取文件,使用 BufferedReader

BufferedReader reader = new BufferedReader(new InputStreamReader(lic));

String line = reader.readLine()
while(line != null){
    System.out.println(line);
    line = reader.readLine();
}

None of the Runtime.exec methods accept an InputStream

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html


To read a file from an InputStream, use a BufferedReader

BufferedReader reader = new BufferedReader(new InputStreamReader(lic));

String line = reader.readLine()
while(line != null){
    System.out.println(line);
    line = reader.readLine();
}
浮生未歇 2024-12-07 03:30:36

我认为这就是您想要做的:

ProcessBuilder pb = new ProcessBuilder("notepad", "/path/to/text-file");
Process process = pb.start();

请参阅 ProcessBuilder Javadocs。

I think this is what you're trying to do:

ProcessBuilder pb = new ProcessBuilder("notepad", "/path/to/text-file");
Process process = pb.start();

See ProcessBuilder Javadocs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文