nix86
nix86

Reputation: 3047

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?

Upvotes: 0

Views: 576

Answers (2)

nix86
nix86

Reputation: 3047

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));

Upvotes: 1

Thomas Broyer
Thomas Broyer

Reputation: 64561

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().

Upvotes: 2

Related Questions