December 31, 2010

Relative Path (Propetries)


PROBLEM:
Project with 2 package - tkorg.idrs.core.searchengines (1) - tkorg.idrs.core.searchengines (2)
In packge (2) i have text file ListStopWords.txt, in packge (1) i have class FileLoadder Here is code in FileLoadder: File file = new File("properties\files\ListStopWords.txt");
But have error :The system cannot find the path specified
Can you give a solution for fix it !
SOLUTION:

If it's already in the classpath, then just obtain it from the classpath. Don't fiddle with relative paths injava.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as FileLoader class:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're after is an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=valuelines) with just the "wrong" extension, then you could feed it immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.classinstead of getClass() in above examples.

 InputStream in = FileLoadder.class.getResourceAsStream("");
    try {
        BufferedReader reader=new BufferedReader(new InputStreamReader(in));
        String line=null;
            while((line=reader.readLine())!=null){
                System.out.println(line);
            }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 
 

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts