The first time I wrote a blog, a simple example: Reading and Writing txt files in java, I hope this is a good start ., Javatxt
As a beginner developer, I search for others' code on the Internet every day, and then repair, modify, and apply the Code to the project. Without knowing it, I became the code Porter.
The fun of programming is to find the code you want in the vast ocean of knowledge, share information, and make it easier for you and others.
The following code is an example of a simple java code reading a txt file. It is simple, but it can be an example for beginners who have no basic knowledge.
Package javatest;
Import java. io. BufferedReader;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. FileOutputStream;
Import java. io. InputStreamReader;
Public class Txt {
/*
* Read txt files
* @ Param fileName: File Name
* @ Return txt content
*/
Public static String readFile (String fileName ){
String fileContent = ""; // Save the txt result
Try {
File f = new File (fileName );
If (f. isFile () & f. exists ()){
InputStreamReader read = new InputStreamReader (
New FileInputStream (f), "UTF-8 ");
BufferedReader reader = new BufferedReader (read );
String line;
While (line = reader. readLine ())! = Null ){
FileContent + = line + "\ n ";
}
Read. close ();
}
} Catch (Exception e ){
E. printStackTrace ();
}
Return fileContent;
}
/*
* Write the content to the txt file.
* @ Param fileName the name of the file to be written
* @ Param Content the data Content written
*/
Public static void writeFile (String fileName, String Content ){
Try {
File f = new File (fileName );
If (! F. exists ()){
F. createNewFile ();
}
FileOutputStream writer = new FileOutputStream (f );
Writer. write (Content. getBytes ("UTF-8 "));
Writer. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
Public static void main (String [] args ){
String content = readFile ("K:/apache1.txt ");
String data = "When is the Spring Festival and autumn? Past events. The building turned east again last night, and the motherland was overwhelmed by looking back at the moon and tomorrow. The building should still be in place, but the landscape should be changed. Q How worried can I be? Just like the spring water flowing eastward. ";
WriteFile ("K: \ .txt", data );
System. out. println (content );
}
}