Summary of java files and streams
1. Read and Write files in Java
Java I/O operations are performed based on streams. To improve read/write efficiency, buffer is required.
A simple example is as follows:
/**
* Read the content in file1 and write it to file2.
*
*/
Bufferedreader reader = new bufferedreader (New filereader (file1 ));
Bufferedwriter writer = new bufferedwriter (New filewriter (file2 ));
String STR = NULL;
STR = reader. Readline ();
While (STR! = NULL)
{
Writer. Write (STR + "/R/N ");
STR = reader. Readline ();
}
Reader. Close ();
Writer. Close ();
Complete example:
Import java. Io .*;
Public class filereading {
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
System. Out. println ("input the direction's path :");
Bufferedreader reader = new bufferedreader (New inputstreamreader (system. In ));
Try
{
String Path = reader. Readline ();
String filename;
Makedir (PATH );
System. Out. println ("input the filename :");
Filename = reader. Readline ();
File file = makefile (path, filename );
Writefile (File );
System. Out. println ("input the file name or the direction :");
Bufferedreader buff = new bufferedreader (New inputstreamreader (system. In ));
File F = new file (buff. Readline (). tostring ());
Listfile (f );
}
Catch (exception ex)
{
System. Err. println (ex. getmessage ());
}
}
Public static void makedir (string path) // create a directory, --- folder
{
Try
{
File file = new file (PATH );
If (! File. exists ())
File. mkdir ();
}
Catch (exception ex)
{
System. Err. println (ex. getmessage ());
}
}
Public static file makefile (string path, string filename) // create a file
{
File F = new file (path, filename );
Try
{
If (! F. exists ())
F. createnewfile ();
}
Catch (exception ex)
{
System. Err. println (ex. getmessage ());
}
Finally
{
Return F;
}
}
Public static void writefile (File file) // write the content in one file to another
{
Try
{
If (! File. exists ())
File. createnewfile ();
Else
{
System. Out. println ("input the file :");
Bufferedreader buff = new bufferedreader (New inputstreamreader (system. In ));
String pathname = buff. Readline ();
File F = new file (pathname );
Bufferedreader reader = new bufferedreader (New filereader (f ));
Bufferedwriter writer = new bufferedwriter (New filewriter (File ));
String STR = NULL;
STR = reader. Readline ();
While (STR! = NULL)
{
Writer. Write (STR + "/R/N ");
STR = reader. Readline ();
}
Reader. Close ();
Writer. Close ();
}
}
Catch (exception ex)
{
System. Err. println (ex. getmessage ());
}
}
Public static void listfile (File file) // list all directories and files
{
File [] list = file. listfiles ();
Int filecout = 0;
Int dircout = 0;
For (file F: List)
{
If (F. isdirectory ())
{
System. Out. println ("this is direction" + (++ dircout) + ":" + F. getname ());
}
Else if (F. isfile ())
{
System. Out. println ("this is file:" + (++ filecout) + ":" + F. getname ());
}
}
}
}