简体   繁体   中英

I can't read a text file in GWT

I am developing a project with GWT and Netbeans. I have an RPC. I have put a text file in the server package "org.myname.server" and I want to read it with a server side method belonging to the class GWTServiceImpl. The text file and the file GWTServiceImpl.java are in the same package. The code is the following:

        String text="";
        try 
        {
            BufferedReader br = new BufferedReader(new FileReader("file.txt"));
            String line;
            while((line = br.readLine()) != null)
            {
                text=text+line;
                System.out.println("here is the line: "+line);
            }
            br.close();
        }
        catch (Exception e) { }
        return text;

It says that it can't access the file. I haven't included the entire path because the file is in the same folder of the method. So why doesn't it work?

File paths aren't relative to “classes”, but to the “current working directory”, so it'll depend how your server is launched, and will likely be different in development and production.

If the file is packaged as a resource in your webapp, then use the appropriate way of loading it: if it's in WEB-INF/classes or in a JAR in WEB-INF/lib , then use getClass().getResourceAsStream("file.txt") ; otherwise use ServletRequest#getResourceAsStream() .

Yes Thomas is right. So in order to create the buffered reader the code is the following:

InputStream is= getClass().getResourceAsStream(filepath);
BufferedReader br = new BufferedReader(new InputStreamReader(is));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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