المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : How can I read from, and write to, files in Java?



A7med Baraka
10-22-2008, 05:42 PM
How can I read from, and write to, files in Java?



Stand-alone applications written in Java can access the local file-system, but applets executing under the control of a browser cannot. With this in mind, lets take a look at two simple applications that write a line of text to a file, and read it back






import java.io.*;

public class MyFirstFileWritingApp
{
// Main method
public static void main (String args[])
{
// Stream to write file
FileOutputStream fout;

try
{
// Open an output stream
fout = new FileOutputStream ("myfile.txt");

// Print a line of text
new PrintStream(fout).println ("hello world!");

// Close our output stream
fout.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
}





This simple application creates a FileOutputStream, and writes a line of text to the file. You'll notice that the file writing code is enclosed within a try { .... } catch block. If you're unfamiliar with exception handling in Java, this requires a little explanation.
Certain methods in Java have the potential to throw an error condition, known as an exception. We have to trap these error conditions, so we 'catch' any exceptions that may be thrown.
The task of reading from a file is also just as easy. We create a FileInputStream object, read the text, and display it to the user.





import java.io.*;

public class MyFirstFileReadingApp
{
// Main method
public static void main (String args[])
{
// Stream to read file
FileInputStream fin;

try
{
// Open an input stream
fin = new FileInputStream ("myfile.txt");

// Read a line of text
System.out.println( new DataInputStream(fin).readLine() );

// Close our input stream
fin.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to read from file");
System.exit(-1);
}
}

}

mansour91b
11-08-2008, 06:31 PM
مشكووووووووووووووووووووووور أخي

م.احمدالامام
04-04-2009, 05:26 PM
Write In File In JAVA




package IOstream;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Writer {
public static void main(String[] args) {
File f=new File("c:/MyFirstFile.txt");
FileWriter fw;
try {
fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Java Developer");
bw.newLine();
bw.close();
System.out.println("Written");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}



}