TechArena Community

TechArena Community (http://forums.techarena.in/)
-   Software Development (http://forums.techarena.in/software-development/)
-   -   How to read and write files in Java (http://forums.techarena.in/software-development/1241022.htm)

BansiJ 02-09-2009 08:29 PM

How to read and write files in Java
 
I am creating a program where the code is able to read a user specified file and also capable of writing few lines in the same file. But how will this be possible using JAVA? How can I code Java for read and write functions? Can anyone explain me the working of this module?

fellah 02-09-2009 08:38 PM

Re: How to read and write files in Java
 
Code:

import java.io.*;

public class ReadWriteFile
{
        public static void main (String args[])
        {
                FileInputStream input;               
                FileOutputStream output;               
                try
                {
                    input = new FileInputStream ("testfile.txt");
                    System.out.println( new DataInputStream(input).readLine() );
                    input.close();               
                }
                try
                {
                    output = new FileOutputStream ("testfile.txt");
                    new PrintStream(output).println ("hello world!");
                    output.close();               
                }
                catch (IOException e)
                {
                        System.err.println ("Unable to read/write file");
                        System.exit(-1);
                }
        }       
}


Katty 02-09-2009 08:45 PM

Re: How to read and write files in Java
 
Here is the code for reading the from the file:

Code:

public void read(String myFile) throws IOException{
        FileReader readFile = null;
        BufferedReader readBuffer;
        String line;
        readFile = new FileReader(myFile);
        readBuffer = new BufferedReader(readFile);
        line=""; 
        while(line != null){       
                line = readBuffer.readLine();               
                System.out.println(line);
        }       
        readBuffer.close();
}


Modifier 02-09-2009 08:52 PM

Re: How to read and write files in Java
 
Here is what I found on SUN.com. To open a file for reading, you can use the newInputStream method. This method returns an unbuffered input stream for reading bytes from the file.

Code:

    Path file = ...;
    InputStream in = null;
    try {
        in = file.newInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException x) {
        System.err.println(x);
    } finally {
        if (in != null) in.close();
    }



All times are GMT +5.5. The time now is 11:51 AM.