Take a note of Java File Operations
1. Write a file based on the file name and string
Public static Boolean writejiang (string content, string path, string name )...{
Try ...{
File file = new file (PATH );
System. Out. println ("file path:" + file + "/" + name );
Bufferedwriter fileout = new bufferedwriter (New filewriter (File + "/" + name, true ));
Fileout. Write (content );
Fileout. Write ("");
Fileout. Flush ();
Fileout. Close ();
}
Catch (exception e )...{
E. printstacktrace ();
}
System. Out. println ("file writing completed ");
Return true;
}
2. Read the file and return a string
Public static string readtxt (string path )...{
String Array = "";
Try ...{
// Read text files
File file = new file (PATH );
Fileinputstream RDF = new fileinputstream (File );
Byte [] S = new byte [RDF. Available ()];
Int B = RDF. Available ();
While (B = RDF. Read (S, 0, B ))! =-1 )...{
String content = new string (S, 0, B );
Array = array + content;
}
RDF. Close ();
}
Catch (exception e )...{
E. printstacktrace ();
}
Return array;
}
3. delete a row in the file. ID is the row number, path + name = File
Public static int deletetxt (string path, string name, int ID )...{
Int result = 0;
String content = "";
Try ...{
// Read the file
Content = readtxt (path + "/" + name );
System. Out. println (path + "/" + name );
System. Out. println ("before the record is deleted, it must be:" + content );
// Delete a row
String [] A = content. Split ("");
Stringbuffer d = new stringbuffer ();
For (Int J = 0; j <A. length; j ++ )...{
If (J! = ID)
D. append (A [J]). append ("");
}
System. Out. println ("after the record is deleted:" + D. tostring ());
// Write the modified data to the file
Writenewtxt (D. tostring (), path, name );
Result = 1;
}
Catch (exception e )...{
E. printstacktrace ();
}
Return result;
}