The Java file output stream is a byte stream class used to process raw binary data. In order to write data to a file, you must convert the data to bytes and save it to a file.
Copy Code code as follows:
Package Com.yiibai.io;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
public class Writefileexample {
public static void Main (string[] args) {
FileOutputStream FOP = null;
File file;
String content = "This is the text content";
try {
File = new file ("C:/newfile.txt");
FOP = new FileOutputStream (file);
If file doesnt exists, then create it
if (!file.exists ()) {
File.createnewfile ();
}
Get the content in bytes
byte[] contentinbytes = Content.getbytes ();
Fop.write (contentinbytes);
Fop.flush ();
Fop.close ();
System.out.println ("Done");
catch (IOException e) {
E.printstacktrace ();
finally {
try {
if (FOP!= null) {
Fop.close ();
}
catch (IOException e) {
E.printstacktrace ();
}
}
}
}
Updated JDK7 For example, use a new "Try resource Shutdown" method to easily process files.
Package Com.yiibai.io;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
public class Writefileexample {
public static void Main (string[] args) {
File File = new file ("C:/newfile.txt");
String content = "This is the text content";
Try (fileoutputstream fop = new FileOutputStream (file)) {
If file doesn ' t exists, then create it
if (!file.exists ()) {
File.createnewfile ();
}
Get the content in bytes
byte[] contentinbytes = Content.getbytes ();
Fop.write (contentinbytes);
Fop.flush ();
Fop.close ();
System.out.println ("Done");
catch (IOException e) {
E.printstacktrace ();
}
}
}