Java read txt file and overwrite write TXT file and append write txt

Source: Internet
Author: User

Package thread;

Import java.io.*;

public class HH {

/**
* Create a file
* @param fileName
* @return
*/
public static Boolean createFile (File fileName) throws exception{
try{
if (!filename.exists ()) {
Filename.createnewfile ();
}
}catch (Exception e) {
E.printstacktrace ();
}
return true;
}


/**
* Read TXT content
* @param file
* @return
*/
public static String readtxtfile (file file) {
String result = "";
try {
InputStreamReader reader = new InputStreamReader (new FileInputStream (file), "GBK");
BufferedReader br = new BufferedReader (reader);
String s = null;
while ((S=br.readline ())!=null) {
Result = result + S;
System.out.println (s);
}
} catch (Exception e) {
E.printstacktrace ();
}
return result;
}


/**
* Write txt, overwrite the original content
* @param content
* @param fileName
* @return
* @throws Exception
*/
public static Boolean writetxtfile (String content,file fileName) throws exception{
Randomaccessfile Mm=null;
Boolean flag=false;
FileOutputStream Fileoutputstream=null;
try {
FileOutputStream = new FileOutputStream (fileName);
Fileoutputstream.write (Content.getbytes ("GBK"));
Fileoutputstream.close ();
Flag=true;
} catch (Exception e) {
E.printstacktrace ();
}
return flag;
}


/**
* Write txt, append write
* @param FilePath
* @param content
*/
public static void Filechasefw (string filePath, string content) {
try {
The second parameter in the constructor true indicates that the file is written in append form
FileWriter FW = new FileWriter (filepath,true);
Fw.write (content);
Fw.close ();
} catch (IOException e) {
System.out.println ("File write Failed! "+ e);
}
}



public static void Main (string[] args) throws exception{
File File = new file ("D:\\123wu ng. txt");
CreateFile (file);
Readtxtfile (file);
Writetxtfile ("I am writing a content one", file);
FILECHASEFW ("D:\\123wu Wu. txt", "66666666");
}
}

Java read txt file and overwrite write TXT file and append write txt

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.