How to scan a file in a different directory in java?

馋奶兔 提交于 2020-01-14 14:59:10

问题


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.


回答1:


By using an absolute path instead of a relative.

File file = new File("C:\\Data\\DataPacket99\\data.txt");

Then you can write code that accesses that file object, using a InputStream or similar.




回答2:


You need to use absolute paths in java.io stuff. Thus not new File("data.txt"), but new 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.




回答3:


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.




回答4:


I would try this:

File file = new File("../../Data/DataPacket99/data.txt");


来源:https://stackoverflow.com/questions/2007503/how-to-scan-a-file-in-a-different-directory-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!