如何将文本文件作为参数传递? [英] How to pass a text file as a argument?

查看:923
本文介绍了如何将文本文件作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个程序来通过args读取文本文件,但是当我运行它时,它总是说文件无法找到,即使我把它放在与我正在运行的main.java相同的文件夹中。
有谁知道我的问题的解决方案或更好的阅读文本文件的方法?

Im trying to write a program to read a text file through args but when i run it, it always says the file can't be found even though i placed it inside the same folder as the main.java that im running. Does anyone know the solution to my problem or a better way of reading a text file?

推荐答案

不要使用 java.io.File 中的相对路径。

Do not use relative paths in java.io.File.

它将变为相对于当前工作目录,这取决于您运行应用程序的方式,而应用程序又无法从应用程序内部进行控制。这只会导致便携性问题。如果从Eclipse内部运行它,路径将相对于 / path / to / eclipse / workspace / projectname 。如果从命令控制台内部运行它,它将相对于当前打开的文件夹(即使您按绝对路径运行代码!)。如果通过双击JAR来运行它,它将相对于JAR的根文件夹。如果您在网络服务器中运行它,它将相对于 / path / to / webserver / binaries 。等等。

It will become relative to the current working directory which is dependent on the way how you run the application which in turn is not controllable from inside your application. It will only lead to portability trouble. If you run it from inside Eclipse, the path will be relative to /path/to/eclipse/workspace/projectname. If you run it from inside command console, it will be relative to currently opened folder (even though when you run the code by absolute path!). If you run it by doubleclicking the JAR, it will be relative to the root folder of the JAR. If you run it in a webserver, it will be relative to the /path/to/webserver/binaries. Etcetera.

始终在 java.io.File 中使用绝对路径,没有任何借口。

Always use absolute paths in java.io.File, no excuses.

为了获得最佳的可移植性和减少绝对路径的麻烦,只需将文件放在运行时类路径覆盖的路径中(或将其路径添加到运行时类路径)。这样你就可以通过 Class#getResource() 或其内容 Class#getResourceAsStream() 。如果它与当前类位于同一文件夹(包)中,则它已经在类路径中。要访问它,只需:

For best portability and less headache with absolute paths, just place the file in a path covered by the runtime classpath (or add its path to the runtime classpath). This way you can get the file by Class#getResource() or its content by Class#getResourceAsStream(). If it's in the same folder (package) as your current class, then it's already in the classpath. To access it, just do:

public MyClass() {
    URL url = getClass().getResource("filename.txt");
    File file = new File(url.getPath());
    InputStream input = new FileInputStream(file);
    // ...
}

public MyClass() {
    InputStream input = getClass().getResourceAsStream("filename.txt");
    // ...
}

这篇关于如何将文本文件作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆