logo

Tworzenie pliku przy użyciu FileOutputStream

Klasa FileOutputStream należy do strumienia bajtów i przechowuje dane w postaci pojedynczych bajtów. Można go używać do tworzenia plików tekstowych. Plik reprezentuje przechowywanie danych na drugim nośniku danych, takim jak dysk twardy lub płyta CD. To, czy plik jest dostępny i czy można go utworzyć, zależy od platformy bazowej. W szczególności niektóre platformy umożliwiają otwieranie pliku do zapisu tylko przez jeden obiekt FileOutputStream (lub inne obiekty zapisujące pliki) na raz. W takich sytuacjach konstruktory w tej klasie zawiodą, jeśli dany plik jest już otwarty. FileOutputStream jest przeznaczony do zapisywania strumieni surowych bajtów, takich jak dane obrazu. Do pisania strumieni znaków rozważ użycie FileWriter. Ważne metody:
    puste zamknięcie(): Zamyka ten strumień wyjściowy pliku i zwalnia wszystkie zasoby systemowe powiązane z tym strumieniem. chroniona pustka finalizuj() : Czyści połączenie z plikiem i zapewnia, że ​​metoda zamknięcia tego strumienia wyjściowego pliku zostanie wywołana, gdy nie będzie już żadnych odniesień do tego strumienia. void write(bajt[] b): Zapisuje b.length bajtów z określonej tablicy bajtów do tego strumienia wyjściowego pliku. void write(byte[] b int off int len): Zapisuje len bajtów z określonej tablicy bajtów, zaczynając od przesunięcia, do tego strumienia wyjściowego pliku. nieważny zapis (int b): Zapisuje określony bajt w strumieniu wyjściowym pliku.
Aby utworzyć plik tekstowy przechowujący niektóre znaki (lub tekst), należy wykonać następujące kroki:
    Odczyt danych: 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 Wyślij dane do 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);
    Odczyt danych z 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);
    Zamknij plik:Na koniec każdy plik powinien zostać zamknięty po wykonaniu na nim operacji wejścia lub wyjścia, w przeciwnym razie dane mogą zostać uszkodzone. Zamknięcie pliku odbywa się poprzez zamknięcie powiązanych strumieni. Na przykład fout.close(): zamknie FileOutputStream, dlatego nie ma możliwości zapisania danych do pliku.
Realizacja: 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); 

Poprawa wydajności za pomocą 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.
  • Załóżmy, że dane są odczytywane z klawiatury do pamięci za pomocą DataInputStream, a wczytanie 1 znaku do pamięci zajmuje 1 sekundę, a znak ten jest zapisywany w pliku przez FileOutputStream, co zajmuje kolejną 1 sekundę.
  • Zatem odczyt i zapis pliku zajmie 200 sekund. To marnowanie dużo czasu. Z drugiej strony, jeśli używane są klasy buforowane, zapewniają one bufor, który jest najpierw wypełniany znakami z bufora, które można od razu zapisać w pliku. Klasy buforowane powinny być używane w połączeniu z innymi klasami strumieniowymi.
  • 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
Ważne metody klasy BufferedOutputStream:
    puste opróżnienie() : Opróżnia buforowany strumień wyjściowy. void write(byte[] b int off int len): Zapisuje len bajtów z określonej tablicy bajtów, zaczynając od przesunięcia, do tego buforowanego strumienia wyjściowego. nieważny zapis (int b): Zapisuje określony bajt w tym buforowanym strumieniu wyjściowym.
Wyjście:
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 
Powiązane artykuły:
  • CharacterStream kontra ByteStream
  • Klasa pliku w Javie
  • Obsługa plików w Javie przy użyciu FileWriter i FileReader
Utwórz quiz