logo

יצירת קובץ באמצעות FileOutputStream

מחלקת FileOutputStream שייכת לזרם בתים ומאחסנת את הנתונים בצורה של בתים בודדים. זה יכול לשמש ליצירת קבצי טקסט. קובץ מייצג אחסון של נתונים על מדיית אחסון שנייה כמו דיסק קשיח או תקליטור. אם קובץ זמין או לא עשוי להיווצר תלוי בפלטפורמה הבסיסית. פלטפורמות מסוימות מאפשרות פתיחת קובץ לכתיבה על ידי FileOutputStream אחד בלבד (או אובייקטים אחרים לכתיבת קבצים) בכל פעם. במצבים כאלה הבנאים במחלקה זו ייכשלו אם הקובץ המעורב כבר פתוח. FileOutputStream מיועד לכתיבת זרמים של בתים גולמיים כגון נתוני תמונה. עבור כתיבת זרמי תווים שקול להשתמש ב-FileWriter. שיטות חשובות:
    void close() : סוגר את זרם פלט הקובץ הזה ומשחרר את כל משאבי המערכת המשויכים לזרם זה. protected void finalize() : מנקה את החיבור לקובץ ומבטיח ששיטת הסגירה של זרם פלט קובץ זה נקראת כאשר אין עוד הפניות לזרם זה. void write(byte[] b) : כותבת בתים b.length ממערך בתים שצוין לזרם פלט הקבצים הזה. void write(byte[] b int off int len) : כותב בתים של len מתוך מערך בתים שצוין החל מ-offset off לזרם פלט הקובץ הזה. void write(int b) : כותב את הביט שצוין לזרם הפלט של הקובץ הזה.
יש לבצע את השלבים הבאים כדי ליצור קובץ טקסט המאחסן כמה תווים (או טקסט):
    קריאת נתונים: First of all data should be read from the keyboard. For this purpose associate the keyboard to some input stream class. The code for using DataInputSream class for reading data from the keyboard is as:
    DataInputStream dis =new DataInputStream(System.in);
    Here System.in represent the keyboard which is linked with DataInputStream object שלח נתונים ל-OutputStream: Now associate a file where the data is to be stored to some output stream. For this take the help of FileOutputStream which can send data to the file. Attaching the file.txt to FileOutputStream can be done as:
    FileOutputStream fout=new FileOutputStream(file.txt);
    קריאת נתונים מ-DataInputStream: The next step is to read data from DataInputStream and write it into FileOutputStream . It means read data from dis object and write it into fout object as shown here:
    ch=(char)dis.read(); fout.write(ch);
    סגור את הקובץ:לבסוף יש לסגור כל קובץ לאחר ביצוע פעולות קלט או פלט עליו, אחרת הנתונים של הקובץ עלולים להיות פגומים. סגירת הקובץ נעשית על ידי סגירת הזרמים המשויכים. למשל fout.close(): יסגור את FileOutputStream ולכן אין דרך לכתוב נתונים לקובץ.
יישום: Java
//Java program to demonstrate creating a text file using FileOutputStream import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException; class Create_File {  public static void main(String[] args) throws IOException   {  //attach keyboard to DataInputStream  DataInputStream dis=new DataInputStream(System.in);  // attach file to FileOutputStream  FileOutputStream fout=new FileOutputStream('file.txt');  //attach FileOutputStream to BufferedOutputStream  BufferedOutputStream bout=new BufferedOutputStream(fout1024);  System.out.println('Enter text (@ at the end):');  char ch;  //read characters from dis into ch. Then write them into bout.  //repeat this as long as the read character is not @  while((ch=(char)dis.read())!='@')  {  bout.write(ch);  }  //close the file  bout.close();  } } 
If the Program is executed again the old data of file.txt will be lost and any recent data is only stored in the file. If we don’t want to lose the previous data of the file and just append the new data to the end of already existing data and this can be done by writing true along with file name.
FileOutputStream fout=new FileOutputStream(file.txttrue); 

שיפור היעילות באמצעות BufferedOutputStream

Normally whenever we write data to a file using FileOutputStream as:
fout.write(ch);
Here the FileOutputStream is invoked to write the characters into the file. Let us estimate the time it takes to read 100 characters from the keyboard and write all of them into a file.
  • נניח שהנתונים נקראים מהמקלדת לתוך הזיכרון באמצעות DataInputStream ולוקח שנייה אחת לקרוא תו אחד לזיכרון ותו זה נכתב לקובץ על ידי FileOutputStream על ידי הוצאה של עוד שנייה אחת.
  • אז לקריאה וכתיבת קובץ ייקח 200 שניות. זה בזבוז זמן רב. מצד שני, אם נעשה שימוש ב-Buffered classed הם מספקים מאגר שמתמלא תחילה בתווים מהמאגר שניתן לכתוב בבת אחת לקובץ. יש להשתמש במחלקות עם מאגר בחיבור למחלקות זרם אחרות.
  • First the DataInputStream reads data from the keyboard by spending 1 sec for each character. This character is written into the buffer. Thus to read 100 characters into a buffer it will take 100 second time. Now FileOutputStream will write the entire buffer in a single step. So reading and writing 100 characters took 101 sec only. In the same way reading classes are used for improving the speed of reading operation.  Attaching FileOutputStream to BufferedOutputStream as:
    BufferedOutputStream bout=new BufferedOutputStream(fout1024);
    Here the buffer size is declared as 1024 bytes. If the buffer size is not specified then a default size of 512 bytes is used
שיטות חשובות של BufferedOutputStream Class:
    void flush() : שוטף את זרם הפלט המאוחסן הזה. void write(byte[] b int off int len) : כותב בתים של עדשה ממערך בתים שצוין החל מ-offset off לזרם הפלט המאוגר הזה. void write(int b): כותב את ה-byte שצוין לזרם הפלט המאוחסן הזה.
תְפוּקָה:
C:> javac Create_File.java C:> java Create_File Enter text (@ at the end): This is a program to create a file @ C:/> type file.txt This is a program to create a file 
מאמרים קשורים:
  • CharacterStream לעומת ByteStream
  • Class File ב-Java
  • טיפול בקבצים ב-Java באמצעות FileWriter ו-FileReader
צור חידון