简体   繁体   English

相对路径与绝对路径Java

[英]Relative vs Absolute Paths Java

I have a programming mini competition tomorrow and we will be required to create our program on a flash drive given. 我明天将参加编程迷你竞赛,我们将需要在给定的闪存驱动器上创建程序。 The judges won't edit our code so it runs and I am worried that the flash drive letter will change and then my program won't be able to locate the text file it needs to read in. 评委不会编辑我们的代码,因此它可以运行,我担心闪存驱动器号会更改,然后我的程序将无法找到需要读取的文本文件。

I have always used paths for my flash drive like this: 我一直为我的闪存驱动器使用以下路径:

FileReader file = new FileReader("E:/BPA/Crypto/input.txt");

Is there a way for me to guarantee my program will be able to read in the text file despite if the letter name for my flash drive isn't the same on the judges computer as it was on mine? 即使法官计算机上的闪存驱动器名称与我的闪存驱动器上的字母名称不同,我是否有办法保证我的程序能够读取文本文件? Thanks! 谢谢!

You may 你可以

  1. Put the file inside your sources 将文件放入您的源中
  2. Use Class.getResourceAsStream(String name) to get InputStream of the file 使用Class.getResourceAsStream(String name)获取文件的InputStream

For example, if you have class xyzA 例如,如果您有类xyzA

  1. Copy input.txt to src folder into x/y/z package input.txt复制到src文件夹到x / y / z包中
  2. Get corresponding InputStreamReader as InputStreamReader fileStream = new InputStreamReader(A.class.getResourceAsStream("input.txt")); 获得相应的InputStreamReader作为InputStreamReader fileStream = new InputStreamReader(A.class.getResourceAsStream("input.txt"));

If you aren't sure what drive the file will be you could do something like this 如果您不确定文件将是哪个驱动器,则可以执行以下操作

    char drive = 'A';
    String filePath = ":/BPA/Crypto/input.txt";
    while(drive != 'Z')
    {
        try{
            Scanner readFromFile = new Scanner(new File(drive + filePath));
            readFromFile.close(); //add this if you simply want the path or drvie letter
            break;
        }catch(FileNotFoundException error)
        {
            System.out.println("Drive: " + drive + " did not contained file in " + drive + filePath);
        }
        drive += 1;
    }

Basically the idea is to attempt to open the file for reading from different drives starting at A up until Y. Obviously you can go further but I am going to assume that drives AY would safely exhaust all the possible drives on where ever you are running your software. 基本上,这个想法是尝试打开文件以从A到Y的不同驱动器进行读取。显然,您可以走得更远,但我将假设AY驱动器将安全地耗尽所有运行您可能运行的驱动器的位置软件。

By the time you get our of the While loop the variable "drive" will contain the correct letter of the drive you want. 在您获得While循环的时间时,变量“ drive”将包含所需驱动器的正确字母。 You can modify it to be a function that returns the letter, or perhaps the file path, or simply use it once whenever you try to read from the text file. 您可以将其修改为返回字母或文件路径的函数,或者在尝试从文本文件读取时仅使用一次。 Up to you. 由你决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM