• (2 Pages)
  • +
  • 1
  • 2

Reading and writing to a file in java Rate Topic: ***** 4 Votes

#1 dragon-slayer  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 93
  • Joined: 06-May 07

Posted 12 May 2007 - 03:29 PM

*
POPULAR

This is a very basic way to write to and read from a file in Java using the java.io package.


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

import java.io.*;

public class File {
    BufferedReader in;
    String read;
 
    public File(){
        try {
            //open a bufferedReader to file helloworld.txt
            in = new BufferedReader(new FileReader("helloworld.txt"));

            //read a line from helloworld.txt and save into a string
            read = in.readLine();

            //print out the line
            System.out.println("file output: " + read);

            //safely close the BufferedReader after use
            in.close();
        }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 to always put it inside a try/catch block that catches an IOException; you'll find this will make it easier as it will output useful error information.

Replace helloworld.txt with the file name you want to read.

This is all good, but what if you want to read a specific line in a File that contains multiple lines? Well it's just as easy.

Let's say 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 it's done

import java.io.*;

public class File {
    BufferedReader in;
    String read;

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

            while(linenum > 0){

                //read the next line until the specific line is found
                read = in.readLine();
                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 that's all for Reading from a file.

.:WRITING TO A FILE:.
Writing to a file in Java is just as easy. This is how it's done

import java.io.*;

public class File {
    BufferedWriter out;
    String read;

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

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

            //flushes and closes the stream
            out.close();
        }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 were writing to, and you will see it will say what you wrote out; in my case Hello 83413. Wait, there seems to be a problem. What happened 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.
import java.io.*;

public class File {
    BufferedWriter out;

    public File(){
        try {
            //replace helloworld.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 = new BufferedWriter(new FileWriter("helloworld.txt",true));

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

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

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

        }
    }

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




There. Now 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 it's a bit shabby it's my first time.

This post has been edited by JackOfAllTrades: 01 November 2010 - 03:08 PM


Is This A Good Question/Topic? 17
  • +

Replies To: Reading and writing to a file in java

#2 William_Wilson  Icon User is offline

  • lost in compilation
  • member icon

Reputation: 205
  • View blog
  • Posts: 4,807
  • Joined: 23-December 05

Posted 14 May 2007 - 06:56 AM

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 :)

Overall, well done!
Was This Post Helpful? 2
  • +
  • -

#3 dragon-slayer  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 93
  • Joined: 06-May 07

Posted 14 May 2007 - 01:00 PM

thanks :) you are completly right about the linenum = 3 thing so I thought about this and it could go something like

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

This post has been edited by dragon-slayer: 14 May 2007 - 01:02 PM

Was This Post Helpful? 2
  • +
  • -

#4 William_Wilson  Icon User is offline

  • lost in compilation
  • member icon

Reputation: 205
  • View blog
  • Posts: 4,807
  • Joined: 23-December 05

Posted 14 May 2007 - 01:03 PM

yup, a line count is exactly what you would have :)

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!
Was This Post Helpful? 1
  • +
  • -

#5 alpha02  Icon User is offline

  • Sexy DIC God
  • member icon

Reputation: 46
  • View blog
  • Posts: 803
  • Joined: 20-May 06

Posted 30 May 2007 - 09:29 AM

Nice tutorial, keep up the good work!
Was This Post Helpful? 0
  • +
  • -

#6 hiphop_13  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 37
  • Joined: 04-June 07

Posted 05 June 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 :)
Was This Post Helpful? 0
  • +
  • -

#7 dragon-slayer  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 93
  • Joined: 06-May 07

Posted 07 June 2007 - 09:39 AM

View Posthiphop_13, on 5 Jun, 2007 - 12:09 AM, said:

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 :)



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
Was This Post Helpful? 0
  • +
  • -

#8 rpd  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 65
  • Joined: 13-August 07

Posted 13 August 2007 - 04:27 AM

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?
Was This Post Helpful? 1
  • +
  • -

#9 1lacca  Icon User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Posted 13 August 2007 - 05:06 AM

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.
Was This Post Helpful? 0
  • +
  • -

#10 blacksnake  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 23-July 07

Posted 16 August 2007 - 05:08 AM

but the question is: how to read and copy the character from the file?
Was This Post Helpful? 0
  • +
  • -

#11 blacksnake  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 23-July 07

Posted 16 August 2007 - 08:20 AM

in your code, how to determine the total number of lines in a file aside from locating the line number in a file?
example:
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
Was This Post Helpful? 0
  • +
  • -

#12 dragon-slayer  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 93
  • Joined: 06-May 07

Posted 22 August 2007 - 06:05 PM

that example was for the code i gave bellow which was:
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();
}
}

Was This Post Helpful? 0
  • +
  • -

#13 blacksnake  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 23-July 07

Posted 25 August 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

This post has been edited by blacksnake: 25 August 2007 - 01:27 AM

Was This Post Helpful? 0
  • +
  • -

#14 dragon-slayer  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 93
  • Joined: 06-May 07

Posted 29 August 2007 - 04:52 PM

View Postblacksnake, on 25 Aug, 2007 - 01:25 AM, said:

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.

This post has been edited by dragon-slayer: 29 August 2007 - 04:53 PM

Was This Post Helpful? 0
  • +
  • -

#15 webbl  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 11-November 07

Posted 11 November 2007 - 08:45 AM

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?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2