Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Java I/O 1

Status
Not open for further replies.

oconv

Programmer
Jan 17, 2002
25
ZA
Hi , I am very very very confused with Java I/O , there are a million classes to use for I/O , from what I could gather , the best for Byte Streams will be:

to wrap FileInputStream in the
DataInputStream for reading
& to wrap FileOutputStream in
DataOutputStream

and for Character Streams
to wrap FileReader in BufferedReader
for reading
& to wrap FileWriter in PrintWriter
for writing

am I on the right track ?? - Please don't be to hard on me I am trying to learn this ;-)

Christiaan
 
Yes, you got it.

As what you stated, java works like this:
1,
For input:
FileInputStream fis = new FileInputStream(f1)
or
FileInputStream fis = new
FileInputStream(¡°C:\\dir\\myfile¡±);
Attempts to open the file; may throw a FileNotFoundException

DataInputStream dis = new DataInputStream(fis); // then add functionality to your program
int i = dis.readInt(); //works if binary, just an example

For output:
FileOutputStream fos = new
FileOutputStream(¡°C:\\dir\\file2¡±);


2,
Text files (strings)
For input:
File f1 = new File(¡°C:\\dir\\myfile.txt¡±);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();

For output:
File f2 = new File(¡°C:\\dir\\newfile.txt¡±);
FileWriter fw = new FileWriter(f2);
PrintWriter pw = new PrintWriter(fw);
pw.println(s);


Hope this can help :)
 
Excellent !!! Thanx a 1000000

now -

you will loop through your file until you get the EOF marker
does the statment - String s = br.readLine();
read line for line

so if your file looks like (where <crlf> = characters for charage return line feed):

this is line 1<crlf>
this is line 2<crlf>
this is line 3<crlf>

s = &quot;this is line 1&quot;
and then s = &quot;this is line 1&quot; and so on and on

 
Correct! But if you would like to read elements(String) within a line, you need the StringTokenizer. It can break the line into elements (Strings), check the API for details.
Good luck!

David
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top