• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 184
  • Last Modified:

How to read a server side file?

I have a servlet application and I need to read a file (simple ascii file) from a valid url (example: http://google.com/book/list.txt), how can I read this file? using FileReader??

Thanks

gp
0
javagirip
Asked:
javagirip
1 Solution
 
CEHJCommented:
Open a URLConnection on it and get its input stream
0
 
bobbit31Commented:
BufferedReader in = null;

try {
    URL myURL = new URL("http://google.com/book/list.txt"));
    URLConnection conn = myURL.openConnection();

    String s;
    String fileText = "";
    in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   while ((s = in.readLine()) != null) {
       fileText += s;
   }
   in.close();
   System.out.println(fileText);
} catch (Exception e) {
   e.printStackTrace();
}
0
 
gkasinathCommented:
Well, because it is a servlet, I am sure you want to send what ever you read from the URL to a client browser that made the request.
To do this connect the output stream of your servlet to the inputstream from the URL connection.
in other words..
  while ((s = in.readLine()) != null) {
      out.println( s );
  }

This will automatically transfer what you read to the waiting client browser..
I hope this helps..
cheers
Lupo
 

0
 
javagiripAuthor Commented:
It worked thanks!

One more question, can I use the same approach to read the file name in a directory? say, I have directory "book" at "http://google.com/book/" how do I read all the file names in that directory?
0
 
bobbit31Commented:
the above code will just store whatever output the url gives... so if you go to http://google.com/book/ in your browser, and it serves you something, then that would be what gets stored in your string.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now