How to scan a file in a different directory in jav

2019-07-02 00:44发布

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.

4条回答
仙女界的扛把子
2楼-- · 2019-07-02 01:12

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-07-02 01:21

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.

查看更多
混吃等死
4楼-- · 2019-07-02 01:35

I would try this:

File file = new File("../../Data/DataPacket99/data.txt");
查看更多
▲ chillily
5楼-- · 2019-07-02 01:36

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.

查看更多
登录 后发表回答