Reading from files in java

J

js_dev

Reading from files

How do I read from a file in Java?
(File input in Java)

(a)
import java.io.FileReader;//import needed

public class Foo{
String s; int c;
public void somefunc(){
.....
FileReader fr = new FileReader("c:\\temp\\debug.txt");
s = new String();
while ( (c=fr.read()) != -1){
s = s + (char)c;
}
//now s contains the file as a string
.....
}
.....
}

or, still better, make it a function for use at any time:

public String readfile(String fullpath){
try{
FileReader fr = new FileReader(fullpath);
s = new String();
while ( (c=fr.read()) != -1){
s = s + (char)c;
}
}catch(Exception e){
System.out.println("Myfile.java|readfile|Exception, text:" + e);
}
return s;
}

(b)
import java.io.FileInputStream;//import needed

public class Foo{
String s; int c;
public void somefunc(){
.....
FileInputStream fis = new FileInputStream("c:\\temp\\debug.txt");
s = new String();
while ( (c=fis.read()) != -1){
s = s + (char)c;
}
//now s contains the file as a string
.....
}
.....
}


(c)
import java.io.RandomAccessFile;//import needed

public class Foo{
.....
public String readfile(String fullpath){
try{
String s = new String();
String temp = new String();
RandomAccessFile raf = new RandomAccessFile(fullpath,"r");
do {
temp = raf.readLine();
if( temp==null ) {
break;
} else {
s = s + temp;
}
} while(true);
raf.close();
}catch (Exception e) {
System.out.println("Myfile.java|readfile|Exception, text:" + e)
}
return s;
}
 
J

Jon Haugsand

* js dev
Reading from files

How do I read from a file in Java?
(File input in Java)

public LinkedList readEntireFile( String filename ) throws
IOException {
BufferedReader br = new BufferedReader(
new FileReader( filename ) );
String line;
LinkedList sb=new LinkedList();
while ( (line=br.readln()) != null ) {
sb.append( line );
}
br.close();
return sb;
}
 
R

Robert Klemme

Jon said:
* js dev

public LinkedList readEntireFile( String filename ) throws
IOException {
BufferedReader br = new BufferedReader(
new FileReader( filename ) );
String line;
LinkedList sb=new LinkedList();
while ( (line=br.readln()) != null ) {
sb.append( line );
}
br.close();
return sb;
}

Some improvements:

public List readEntireFile( String filename ) throws
IOException {
BufferedReader br = new BufferedReader(
new FileReader( filename ) );

try {
String line;
LinkedList sb=new LinkedList();
while ( (line=br.readline()) != null ) {
sb.add( line );
}
return sb;
}
finally {
try { br.close(); } catch ( IOException ignore ) {}
}
}

robert
 
T

Thomas Hawtin

Robert said:
Some improvements:

public List readEntireFile( String filename ) throws
IOException {
BufferedReader br = new BufferedReader(
new FileReader( filename ) );

try {
String line;
LinkedList sb=new LinkedList();
while ( (line=br.readline()) != null ) {
sb.add( line );
}
return sb;
}
finally {
try { br.close(); } catch ( IOException ignore ) {}
}
}

Some improvements:

// Note we are using the default character encoding,
// which is probably wrong.
public static List<String> readFileFully(
String filename
) throws IOException {
Reader rawReader = new FileReader(filename);
try {
BufferedReader reader = new BufferedReader(
rawReader
}
List<String> lines = new ArrayList<String>();
for (;;) {
String line = reader.readLine();
if (line == null) {
return lines;
}
lines.add(line);
}
} finally {
rawReader.close();
}
}

Usual disclaimer.

Tom Hawtin
 
R

Robert Klemme

Thomas said:
Some improvements:

// Note we are using the default character encoding,
// which is probably wrong.
public static List<String> readFileFully(
String filename
) throws IOException {
Reader rawReader = new FileReader(filename);
try {
BufferedReader reader = new BufferedReader(
rawReader
}
List<String> lines = new ArrayList<String>();
for (;;) {
String line = reader.readLine();
if (line == null) {
return lines;
}
lines.add(line);
}
} finally {
rawReader.close();
}
}

Usual disclaimer.

- works only with Java 1.5 and later

IMHO it's cleaner to close the BufferedReader because then it has a chance
to do cleanup. Also closing is propagated so the file handle gets
released. Also, IMHO it's better to catch IOException on close() to not
mask other exceptions throwing from the block.

Kind regards

robert
 
R

Robert Klemme

Robert said:
- works only with Java 1.5 and later

IMHO it's cleaner to close the BufferedReader because then it has a
chance to do cleanup. Also closing is propagated so the file handle
gets released. Also, IMHO it's better to catch IOException on
close() to not mask other exceptions throwing from the block.

PS: LinkedList is more efficient than ArrayList for large files because an
ArrayList needs frequent reallocations of the whole internal array.

robert
 
T

Thomas Hawtin

If you were learning Java why would you use a version that is almost a
year out of date already? Nuts.

I did use BufferedReader. It doesn't do any useful cleanup other than
getting the FileReader to cleanup. Might as well just close the FileReader.

Your code isn't exception safe. The BufferedReader throwing an exception
would cause the file handle to be subject to the vagaries of finalisation.

If close throws an exception, it should be reported. It may be that the
FileReader threw an exception, in which case any close exception would
just duplicate the exception that was lost. If it was something else,
then it's still more significant that the physical resource has issues.
PS: LinkedList is more efficient than ArrayList for large files because an
ArrayList needs frequent reallocations of the whole internal array.

Not true. Even got mentioned on a few blogs recently. CompScis and their
bad algorithms...

ArrayList isn't as good as Vector in this respect. However, when it
reallocates it goes for a 50% increase in capacity rather than a fixed
step. This means that the cost of reallocation is approximately
proportional to size.

So ArrayList will allocate a total of, say, four times what was
necessary. LinkedList on the other hand allocate an entry of, say, six
times what is needed (reference + next link + previous link + header
(perhaps, class pointer + hashCode + gubbins)). Worse, it's not thrown
away like the vast majority of ArrayList's excesses. And has a decidedly
detrimental effect on garbage collection, particularly pauses.

There are very few instances where LinkedList is better than ArrayList.
The main use of linked lists is to confuse CompSci first years.

Tom Hawtin

FWIW, at University I was chucked out of the Engineering faculty for
failing CompSci first year.
 
T

Thomas Hawtin

I wrote a series of Java Basics articles , and this on is on reading
files:
http://jdj.sys-con.com/read/38333.htm

Regards,
Yakov Fain
http://www.weekendwithexperts.com

Looking at your first example:

< FileInputStream myFile = null;
< try {
< myFile = new FileInputStream("abc.dat"); // open the stream
< ...
< } catch (IOException e) {
< System.out.println("Could not read file: " + e.toString());
< } finally{
< try{
< myFile.close(); // close the stream

What do you think is going to happen if the file is not found?

< } catch (Exception e1){
< e1.printStackTrace();
< }
< }

Tom Hawtin
 
T

Thomas Hawtin

Tom,
You're right, I missed it here :(

But I did explained this situation in my piece on Exceptions (read the
Try/Catch section in http://jdj.sys-con.com/read/38160.htm )

I'm not sure we are talking about hte same thing.

I've taken you code and wrapped in the usual. Try running it *without*
the file abc.dat.

import java.io.*;

class NotMyFile {
public static void main(String[] args) {
FileInputStream myFile = null;
try {
myFile = new FileInputStream("abc.dat"); // open the stream
boolean eof = false;

while (!eof) {
int byteValue = myFile.read(); // read the stream
System.out.print(byteValue + " ");
if (byteValue == -1)
eof = true;
}
//myFile.close(); // do not do it here!!!
} catch (IOException e) {
System.out.println("Could not read file: " + e.toString());
} finally{
try{
myFile.close(); // close the stream
} catch (Exception e1){
e1.printStackTrace();
}
}
}
}

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top