Full Version: Reading and writing to a file in java
Dream.In.Code > Programming Tutorials > Java Tutorials
dragon-slayer
There is a very basic way in writing and reading to a file in java using the java.io pakage.


Firstly we shell cover reading a file
.:READING:.

CODE

import java.io.*;

public class File {
BufferedReader in;
String read;

  public File(){
try {
in = new BufferedReader(new FileReader("helloworld.txt"));//open a bufferedReader to file hellowrold.txt
read = in.readLine();//read a line from helloworld.txt and save into a string
System.out.println("file output: " + read);//print out the line
in.close();//safley close the BufferedReader after use
}catch(IOException e){
System.out.println("There was a problem:" + e);

}
}

public static void main(String[] args){
File File = new File();
}
}


Easy as that.Remember when handling a BufferedReader always put it inside a try method that catches an IOException , you'll find this will make it easier as it will output useful error information.

replace helloworld.txt with the filename you want to read.

This is all good but what if you want to read a specific line in a File that containts multiple lines.

well its just as easy lets says helloworld.txt contains this:
hello world
hello keyboard
hello mouse
hello test
and i want to read line 3 which is "hello mouse":

this is how its done

CODE


import java.io.*;

public class File {
BufferedReader in;
String read;
int linenum = 3;//the specfic line i want to read
  public File(){
try {
in = new BufferedReader(new FileReader("helloworld.txt"));

while(linenum > 0){

read = in.readLine();//read the next line until the specfic line is found

linenum--;
}

System.out.println("file output: " + read);
in.close();
}catch(IOException e){
System.out.println("There was a problem:" + e);

}
}

public static void main(String[] args){
File File = new File();
}
}

Easy isn't it replace the integer for linenum to the specific line you which to read.

And thats all for Reading from a file.

.:WRITING TO A FILE:.
Writing to a file in java is just as easy this is how its done

CODE


import java.io.*;

public class File {
BufferedWriter out;
String read;

int linenum = 3;//the specfic line i want to read
  public File(){
try {
out = new BufferedWriter(new FileWriter("helloworld.txt"));//replace hellowrold.txt with the name of the file

out.write("Hello 83743");//Write out the specfied string to the file





out.close();//flushes and closes the stream
}catch(IOException e){
System.out.println("There was a problem:" + e);

}
}

public static void main(String[] args){
File File = new File();
}
}

Yep that easy,run this then open the file you where writting to,as you will see it will say what you wrote out in my case Hello 83413,wait there seems to be a problem what happend to the rest of the lines:0,well there is an easy fix for that:)

This is how you can write to a file without erasing its content.
CODE


import java.io.*;

public class File {
BufferedWriter out;

  public File(){
try {
out = new BufferedWriter(new FileWriter("helloworld.txt",true));//replace hellowrold.txt with the name of the file CHANGE after
//you declare which file to write to add the boolean true which will stop it from replacing the helloworld.txt with a new one.



out.write("Hello you stupid duck");//Write out a string to the file

out.newLine();//write a new line to the file so the next time you write to the file it does it on the next line



out.close();//flushes and closes the stream
}catch(IOException e){
System.out.println("There was a problem:" + e);

}
}

public static void main(String[] args){
File File = new File();
}
}

There know every time you write to the file it will keep its contents and write to the next line:)
Thanks for reading my tutorial sorry if its a bit shabby its my first time.
William_Wilson
not a bad tutorial, but i think the finding of a line should be done in another way, than simply:
int linenum = 3;//the specfic line i want to read
since, if the file does not have 3 lines, this will throw an exception. I realize it will be caught, but it is something which could be handled ahead of time.
(Just something to think about)

I also wanted to comment, that the classname File is not the best choice as this class already exists in java.

I am a fan of the bufferedReader myself, over the other options. I think i even used it in some of my snippets smile.gif

Overall, well done!
dragon-slayer
thanks smile.gif you are completly right about the linenum = 3 thing so I thought about this and it could go something like

CODE

int linenum2 = 0;

String temp;
        while ((temp = in.readLine()) != null) {

            linenum2++;



        }
      

which if im right should calculate how much lines they are in a file(i think if im wrong say:)) :)Thanks again for pointing that out i hope to write more detaild tutoirals in the future
William_Wilson
yup, a line count is exactly what you would have smile.gif

It's good to see an interest in sharing knowledge. I know from experience, that files can be a tricky subject for new/inexperienced java programmers, and an example and explanation is exactly what they need to learn properly.
Keep it up!
alpha02
Nice tutorial, keep up the good work!
hiphop_13
hey im new to file reading and writing issues, i would appreciate any help on how to read an int, double,char.. from a file

i want to write to a file an int id char type int miles int time
then i want to read the miles and time to use tem for calculatingf the efficiency which is miles/time

thanks for help smile.gif
dragon-slayer
QUOTE(hiphop_13 @ 5 Jun, 2007 - 12:09 AM) *

hey im new to file reading and writing issues, i would appreciate any help on how to read an int, double,char.. from a file

i want to write to a file an int id char type int miles int time
then i want to read the miles and time to use tem for calculatingf the efficiency which is miles/time

thanks for help smile.gif



Hello,If i where you I would write the numbers out as a string.
Then read it as a string but just convert it from string to int.This can be done by using the Integer.parseInt(); function.For example you have just written 20 on the first line which repesents the miles.
so when you read it you do int miles = Integer.parseInt(in.readLine());
I hope this helps
rpd
The code you give for reading a file reads a line only(using readLine)from the file. What code is needed to read the whole file?
1lacca
I would suggest putting close method into a finally close, so if an IOException is raised, the file is still closed. (This way it isn't, although when the object is finalized, it probably happens)
Also, choosing a name for your class (File) that is the same as an often used core Java class, is probably not a good idea. Anyway, just my 2 cents.
blacksnake
but the question is: how to read and copy the character from the file?
blacksnake
in your code, how to determine the total number of lines in a file aside from locating the line number in a file?
example:
CODE

import java.io.*;

public class File {
BufferedReader in;
String read;

  public File(){
try {
in = new BufferedReader(new FileReader("helloworld.txt"));//open a bufferedReader to file hellowrold.txt
read = in.readLine();//read a line from helloworld.txt and save into a string
System.out.println("file output: " + read);//print out the line
in.close();//safley close the BufferedReader after use
}catch(IOException e){
System.out.println("There was a problem:" + e);

}
}

public static void main(String[] args){
File File = new File();
}
}


the output should be:
hello world
hello keyboard
hello mouse
hello test
Number of lines: 4

dragon-slayer
that example was for the code i gave bellow which was:
CODE
import java.io.*;

public class File {
BufferedReader in;
String read;
int linenum = 3;//the specfic line i want to read
  public File(){
try {
in = new BufferedReader(new FileReader("helloworld.txt"));

while(linenum > 0){

read = in.readLine();//read the next line until the specfic line is found

linenum--;
}

System.out.println("file output: " + read);
in.close();
}catch(IOException e){
System.out.println("There was a problem:" + e);

}
}

public static void main(String[] args){
File File = new File();
}
}
blacksnake
another thing is to how to tokenized those strings and scans each character in a whole file
assuming the content of test.txt is:
1 2 3 4 5 6
7 8 8 9 9 0
NOTE: assuming that tokenized a string is implemented
it looks like this:
1
2
3
4
5
6
7
8
8
9
9
0

not:
print:
1
2
3
4
5
6
print:
7
8
8
9
9
0
dragon-slayer
QUOTE(blacksnake @ 25 Aug, 2007 - 01:25 AM) *

another thing is to how to tokenized those strings and scans each character in a whole file
assuming the content of test.txt is:
1 2 3 4 5 6
7 8 8 9 9 0
NOTE: assuming that tokenized a string is implemented
it looks like this:
1
2
3
4
5
6
7
8
8
9
9
0

not:
print:
1
2
3
4
5
6
print:
7
8
8
9
9
0


Do you mean like only print part of the file if thats what you mean you could do something like this
text.txt
1
2
3
4
5
6
[brake-here]
7
8
8
9
9
0

pseudocode
while(readLine(Text.txt) != null){
if (readLine(Text.txt) != "brake-here"){
skipLine(Text.txt)

}
else{
boolean startToPrint = true;
skipLine(Text.txt)
}
if(startToPrint = true){
System.out.println(readLine(text.txt);
}
}

Sorry I could not give you the java code but you can easily just look at this example and implement it in java.
webbl
CODE

import java.io.*;

public class File {
BufferedReader in;
String read;

  public File(){
try {
in = new BufferedReader(new FileReader("helloworld.txt"));//open a bufferedReader to file hellowrold.txt
read = in.readLine();//read a line from helloworld.txt and save into a string
System.out.println("file output: " + read);//print out the line
in.close();//safley close the BufferedReader after use
}catch(IOException e){
System.out.println("There was a problem:" + e);

}
}

public static void main(String[] args){
File File = new File();

}
}


how would you go about to make the file show all the names within the file?
Ziz
Hi can u please explain how to save tokenized items.
that is i've read the item from a file and tokenized but then I want to save it so I can work with the data later on, how do I do that?
blacksnake
a tokenized item followed by a newline and append it into the string ......... and save it to the file.... can you show the code based on my algorithm?
AFTERGLOW
thanks for the good work . icon_up.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.