how to read text file relative path

喜欢而已 提交于 2020-01-01 04:36:30

问题


I have read sources here & there, but did not get the following code working. Basically, I wish to read a text file, named 'Administrator' from the folder 'src'. I will need a relative path, since this project may be transferred to another person. Please be patient with me.

public void staffExists () throws IOException
    {               
        //http://stackoverflow.com/questions/2788080/reading-a-text-file-in-java
        BufferedReader reader = new BufferedReader(new FileReader(getClass().getResourceAsStream ("/DBTextFiles/Administrator.txt")));

        try
        {               
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                if (!(line.startsWith("*")))
                {
                    System.out.println(line);
                }
            }

        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }               

        finally
        {
            reader.close();
        }           
    }

回答1:


This is a valid absolute path (on the systems I'm aware of):

    /path/to/directory/../../otherfolder/etc/

So what the other answer was saying, was to get the path to the current directory with:

    String filePath = new File("").getAbsolutePath();

Then concatenate your relative path with:

    filePath.concat("path to the property file");



回答2:


Now I get it, somewhat answers here & there do help in getting me to the goal. Did a short edit to my code & it worked. Hope it'll also help some poor souls out there.

String filePath = new File("").getAbsolutePath();
System.out.println (filePath);

//http://stackoverflow.com/questions/2788080/reading-a-text-file-in-java    
//http://stackoverflow.com/questions/19874066/how-to-read-text-file-relative-path
BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Administrator.txt"));

try
{                           
    String line = null;         
    while ((line = reader.readLine()) != null)
    {
        if (!(line.startsWith("*")))
        {
            System.out.println(line);
        }
    }               
}
catch (IOException ex)
{
    ex.printStackTrace();
}               

finally
{
    reader.close();
}                   



回答3:


This is not correct:

new FileReader(getClass().getResourceAsStream ("/DBTextFiles/Administrator.txt"))

You want:

new InputStreamReader(getClass().getResourceAsStream ("/DBTextFiles/Administrator.txt"))



回答4:


In almost all cases you should use the portable forward slash "/"." In every case you should use either the File constructor that accepts a File (parent) & String (file name) or use System.getProperty("file.separator").



来源:https://stackoverflow.com/questions/19874066/how-to-read-text-file-relative-path

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