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?
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);
}
}
}
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();
}
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();
}