java中如何扫描不同目录下的文件?
如何使用java扫描不在java文件所在目录中的文件?
例如:java文件位于“C:\Files\JavaFiles\test.java” 但是,我要扫描的文件位于“C:\Data\DataPacket99\data.txt”
注意:我已经尝试将另一个 java 文件放入“C:\Data”目录中并使用 test.java 文件作为类,但它不起作用。它仍然尝试从“C:\Files\JavaFiles”目录进行扫描。
How do you scan a file with java that isn't in the directory the java file is in?
For example: The java file is located at "C:\Files\JavaFiles\test.java" However, the file I want to scan is located at "C:\Data\DataPacket99\data.txt"
Note: I've already tried putting another java file in the "C:\Data" directory and using the test.java file as a class, but it doesn't work. It still tries to scan from the "C:\Files\JavaFiles" Directory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过使用绝对路径而不是相对路径。
然后,您可以使用 InputStream 或类似的方法编写访问该文件对象的代码。
By using an absolute path instead of a relative.
Then you can write code that accesses that file object, using a InputStream or similar.
您需要在 java.io 中使用绝对路径。因此,不是
new File("data.txt")
,而是new File("C:/Data/DataPacket99/data.txt")
。否则,它将相对于当前工作目录,而当前工作目录本身在所有环境或您期望的环境中可能并不相同。You need to use absolute paths in java.io stuff. Thus not
new File("data.txt")
, butnew File("C:/Data/DataPacket99/data.txt")
. Otherwise it will be relative to the current working directory which may not per-se be the same in all environments or the one you'd expect.您应该使用绝对路径而不是相对路径。
您可以使用
File file = new File("C:/Data/DataPacket99/data.txt");
但使用 文件选择器对话框(如果用户在任何时候都必须输入文件路径)。You should be using an absolute path instead of a relative path.
You could use
File file = new File("C:/Data/DataPacket99/data.txt");
but it might make your life easier in the future to use a file chooser dialog if at any point the user will have to enter a file path.我会尝试这个:
I would try this: