Read and Write operations on files in Java summarized by myself

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.