Copy Code code as follows:
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.PrintStream;
Import Java.io.PrintWriter;
Import Java.io.RandomAccessFile;
public class Writestringtotxt {
public void Writestringtofile (String filePath) {
try {
file File = new file (FilePath);
PrintStream PS = new PrintStream (new FileOutputStream (file));
ps.println ("http://www.jb51.net"); Writes a string to the file
ps.append ("Http://www.jb51.net" //On existing basis add string
} catch (FileNotFoundException e) {
//TODO auto-generated catch block
E.printstacktrace ();
}
}
public void WriteStringToFile2 (String filePath) {
try {
FileWriter FW = new FileWriter (FilePath, true);
BufferedWriter bw = new BufferedWriter (FW);
Bw.append ("Add a string on an existing basis");
Bw.write ("abc\r\n");//Add string to existing file
Bw.write ("def\r\n");
Bw.write ("Hijk");
Bw.close ();
Fw.close ();
catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
public void WriteStringToFile3 (String filePath) {
try {
printwriter pw = new PrintWriter ( New FileWriter (FilePath));
pw.println ("abc");
pw.println ("def");
pw.println ("Hef");
pw.close ();
} catch (IOException e) {
//TODO auto-generated catch block
E.printstacktrace ();
}
}
public void WriteStringToFile4 (String filePath) {
try {
randomaccessfile RF = new Randomaccessfile (FilePath, "RW");
rf.writebytes ("op\r\n");
rf.writebytes ("app\r\n");
rf.writebytes ("hijklllll");
rf.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
public void WriteStringToFile5 (String filePath) {
try {
fileoutputstream fos = new FileOutputStream (FilePath);
String s = "Http://www.jb51.netl";
Fos.write (S.getbytes ());
fos.close ();
} catch (Exception e) {
//TODO auto-generated catch block
E.printstacktrace ();
}
}
public static void Main (string[] args) {
String FilePath = "E:\\link.txt";
New Writestringtotxt (). Writestringtofile (FilePath);
New Writestringtotxt (). WriteStringToFile2 (FilePath);
New Writestringtotxt (). WriteStringToFile3 (FilePath);
New Writestringtotxt (). WriteStringToFile4 (FilePath);
New Writestringtotxt (). WriteStringToFile5 (FilePath);
}
}