logo

Създаване на файл с помощта на FileOutputStream

Класът FileOutputStream принадлежи към потока от байтове и съхранява данните под формата на отделни байтове. Може да се използва за създаване на текстови файлове. Файлът представлява съхранение на данни на втори носител за съхранение като твърд диск или компактдиск. Дали даден файл е наличен или може да бъде създаден зависи от основната платформа. Някои платформи по-специално позволяват файлът да бъде отворен за запис само от един FileOutputStream (или други обекти за запис на файл) наведнъж. В такива ситуации конструкторите в този клас ще се провалят, ако участващият файл вече е отворен. FileOutputStream е предназначен за запис на потоци от необработени байтове, като например данни за изображения. За писане на потоци от знаци помислете за използването на FileWriter. Важни методи:
    void close(): Затваря този изходен поток на файла и освобождава всички системни ресурси, свързани с този поток. защитена празнина finalize() : Изчиства връзката към файла и гарантира, че методът за затваряне на този изходен поток на файл се извиква, когато няма повече препратки към този поток. void write(byte[] b) : Записва b.length байтове от указания масив от байтове в този изходен поток на файла. void write(byte[] b int off int len) : Записва len байтове от посочения масив от байтове, започвайки от отместване, в този изходен поток на файл. 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 и отнема 1 секунда, за да се прочете 1 знак в паметта и този знак се записва във файла от FileOutputStream, като се изразходва още 1 секунда.
  • Така че за четене и запис на файл ще отнеме 200 секунди. Това е загуба на много време. От друга страна, ако се използват буферирани класове, те осигуряват буфер, който първо се запълва със знаци от буфера, които могат веднага да бъдат записани във файла. Буферираните класове трябва да се използват във връзка с други класове на потока.
  • 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:
    void flush(): Промива този буфериран изходен поток. void write(byte[] b int off int len) : Записва len байтове от указания масив от байтове, започвайки от отместване, в този буфериран изходен поток. void write(int b) : Записва посочения байт в този буфериран изходен поток.
Изход:
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
  • Файлов клас в Java
  • Работа с файлове в Java с помощта на FileWriter и FileReader
Създаване на тест