สตรีมเอาต์พุตไฟล์ Java เป็นคลาสสตรีมไบต์ที่ใช้ในการประมวลผลข้อมูลไบนารีดิบ ในการเขียนข้อมูลไปยังไฟล์ข้อมูลจะต้องถูกแปลงเป็นไบต์และบันทึกลงในไฟล์
การคัดลอกรหัสมีดังนี้:
แพ็คเกจ com.yiibai.io;
นำเข้า Java.io.File;
นำเข้า Java.io.FileOutputStream;
นำเข้า java.io.ioException;
คลาสสาธารณะ WriteFileExample {
โมฆะคงที่สาธารณะหลัก (สตริง [] args) {
fileOutputStream fop = null;
ไฟล์ไฟล์;
String Content = "นี่คือเนื้อหาข้อความ";
พยายาม {
ไฟล์ = ไฟล์ใหม่ ("c:/newfile.txt");
FOP = ใหม่ fileOutputStream (ไฟล์);
// ถ้าไฟล์ไม่มีอยู่ให้สร้างมัน
if (! file.exists ()) {
file.createnewfile ();
-
// รับเนื้อหาเป็นไบต์
ไบต์ [] contentInbytes = content.getBytes ();
fop.write (ContentInbytes);
fop.flush ();
fop.close ();
System.out.println ("เสร็จสิ้น");
} catch (ioexception e) {
E.PrintStackTrace ();
} ในที่สุด {
พยายาม {
ถ้า (fop! = null) {
fop.close ();
-
} catch (ioexception e) {
E.PrintStackTrace ();
-
-
-
-
ตัวอย่างเช่น // updated JDK7 ใช้วิธีการ "Try Resource Shutdown" ใหม่เพื่อประมวลผลไฟล์ได้อย่างง่ายดาย
แพ็คเกจ com.yiibai.io;
นำเข้า Java.io.File;
นำเข้า Java.io.FileOutputStream;
นำเข้า java.io.ioException;
คลาสสาธารณะ WriteFileExample {
โมฆะคงที่สาธารณะหลัก (สตริง [] args) {
ไฟล์ไฟล์ = ไฟล์ใหม่ ("c:/newfile.txt");
String Content = "นี่คือเนื้อหาข้อความ";
ลอง (fileOutputStream fop = ใหม่ fileOutputStream (ไฟล์)) {
// ถ้าไฟล์ไม่มีอยู่ให้สร้างมัน
if (! file.exists ()) {
file.createnewfile ();
-
// รับเนื้อหาเป็นไบต์
ไบต์ [] contentInbytes = content.getBytes ();
fop.write (ContentInbytes);
fop.flush ();
fop.close ();
System.out.println ("เสร็จสิ้น");
} catch (ioexception e) {
E.PrintStackTrace ();
-
-
-