f



Reading from files in java

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

0
js_dev (53)
8/26/2005 11:12:22 AM
comp.lang.java.programmer 52711 articles. 1 followers. Post Follow

11 Replies
407 Views

Similar Articles

[PageSpeed] 48

* 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;
}



-- 
Jon Haugsand
  Dept. of Informatics, Univ. of Oslo, Norway, mailto:jonhaug@ifi.uio.no
  http://www.ifi.uio.no/~jonhaug/, Phone: +47 22 85 24 92
0
jonhaug (77)
8/26/2005 11:51:29 AM
Jon Haugsand wrote:
> * 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;
> }

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

0
bob.news (3807)
8/26/2005 12:41:01 PM
Robert Klemme wrote:
> Jon Haugsand wrote:
> 
>>* 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;
>>}
> 
> 
> 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
-- 
Unemployed English Java programmer
http://jroller.com/page/tackline/
0
usenet120 (1728)
8/26/2005 1:41:45 PM
Thomas Hawtin wrote:
> Robert Klemme wrote:
>> Jon Haugsand wrote:
>>
>>> * 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;
>>> }
>>
>>
>> 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.

 - 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


0
bob.news (3807)
8/26/2005 2:20:52 PM
Robert Klemme wrote:
> Thomas Hawtin wrote:
>> Robert Klemme wrote:
>>> Jon Haugsand wrote:
>>>
>>>> * 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;
>>>> }
>>>
>>>
>>> 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.
>
>  - 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

0
bob.news (3807)
8/26/2005 2:23:10 PM
Robert Klemme wrote:
> Robert Klemme wrote:
> 
>>Thomas Hawtin wrote:
>>
>>>Robert Klemme wrote:
>>>>
>>>>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();
>>>     }
>>>}
>>
>> - works only with Java 1.5 and later

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

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

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.

>>                Also, IMHO it's better to catch IOException on
>>close() to not mask other exceptions throwing from the block.

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.
-- 
Unemployed English Java programmer
http://jroller.com/page/tackline/
0
usenet120 (1728)
8/26/2005 3:45:22 PM
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


Thomas Hawtin wrote:
> Robert Klemme wrote:
> > Robert Klemme wrote:
> >
> >>Thomas Hawtin wrote:
> >>
> >>>Robert Klemme wrote:
> >>>>
> >>>>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();
> >>>     }
> >>>}
> >>
> >> - works only with Java 1.5 and later
>
> If you were learning Java why would you use a version that is almost a
> year out of date already? Nuts.
>
> >>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.
>
> 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.
>
> >>                Also, IMHO it's better to catch IOException on
> >>close() to not mask other exceptions throwing from the block.
>
> 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.
> --
> Unemployed English Java programmer
> http://jroller.com/page/tackline/

0
yakovfain (26)
8/26/2005 5:36:38 PM
yakovfain@gmail.com wrote:
> 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
-- 
Unemployed English Java programmer
http://jroller.com/page/tackline/
0
usenet120 (1728)
8/26/2005 7:22:26 PM
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 )

But thank you for the catch.

Yakov

0
yakovfain (26)
8/26/2005 8:13:01 PM
yakovfain@gmail.com wrote:
> 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
-- 
Unemployed English Java programmer
http://jroller.com/page/tackline/
0
usenet120 (1728)
8/26/2005 8:37:22 PM
On 26 Aug 2005 04:12:22 -0700, js_dev@rediffmail.com wrote or quoted :

>How do I read from a file in Java?

there are hundreds of ways of doing it.  For the one you need, consult
the File I/O Amanuensis.

See http://mindprod.com/applets/fileio.html

-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
0
look-on (4215)
8/26/2005 9:26:19 PM
Reply: