Advertisement

[java] Opening Text Files

Started by April 26, 2001 12:36 PM
1 comment, last by capn_midnight 23 years, 9 months ago
Is there somethng like C''s fopen() in java? If not, is it at all possible to read from an external file in Java? AOL, so easy to use, no wonder it''s nothing but a bunch of retards

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

Yes, it is possible (very) to do file i/o with Java. You may want to check out sun's Java doc and look at the "java.io" package.
(http://java.sun.com/j2se/1.3/docs/api/index.html)

But here is ONE method to open a text file with Java:
    BufferedReader ds = null;URL u;String line;// the file name, must have the path. // since were creating a url object you have to have  // http:// or file:///, etc. String fileName = "file:///C:/path/myFile.txt"// open the filetry {  u = new URL(asc);  ds = new BufferedReader(new InputStreamReader(u.openStream()));}catch(Exception e) {}// read from the filewhile(true) {  try {     line = ds.readLine();     if(line == null)break;  }catch(IOException e) {}  //end try}// close the filetry {  ds.close(); }catch(IOException e) {}  


As I mentioned above this is not the only way to read files in java. This may not be even the easiest. I use this method in my applets that require to read files over the net.

Actually for my java apps I use the classes ObjectInputStream and ObjectOutputStream to have a more robust method for file i/o. Check these classes out and how to use them at the site I mentioned above.

Cheers, JP.

Edited by - loserkid on April 26, 2001 6:57:43 PM
==============================================I feel like a kid in some kind of store... ============================================== www.thejpsystem.com
Advertisement
basically for reading in lines as strings you do this:

String file = "fileName.txt"
OR
File file = new File("fileName.txt");


BufferedReader buffer = new BufferedReader(new FileReader(file));

now you can read from buffer like so:

String s = buffer.readLine();//returns null at end of file


both the creation and the reading throw exceptions so just wrap them in methods

This topic is closed to new replies.

Advertisement