Archived

This topic is now archived and is closed to further replies.

capn_midnight

[java] Opening Text Files

Recommended Posts

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

Share this post


Link to post
Share on other sites
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 file

try {
u = new URL(asc);
ds = new BufferedReader(new InputStreamReader(u.openStream()));
}catch(Exception e) {}

// read from the file

while(true) {
try {
line = ds.readLine();
if(line == null)break;
}catch(IOException e) {} //end try

}

// close the file

try {
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

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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

Share this post


Link to post
Share on other sites