Android studio fileoutputstream to file

Android studio fileoutputstream to file

Запись файлов и класс FileOutputStream

Класс FileOutputStream предназначен для записи байтов в файл. Он является производным от класса OutputStream, поэтому наследует всю его функциональность.

Через конструктор класса FileOutputStream задается файл, в который производится запись. Класс поддерживает несколько конструкторов:

Файл задается либо через строковый путь, либо через объект File. Второй параметр — append задает способ записи: eсли он равен true, то данные дозаписываются в конец файла, а при false — файл полностью перезаписывается

Например, запишем в файл строку:

Для создания объекта FileOutputStream используется конструктор, принимающий в качестве параметра путь к файлу для записи. Если такого файла нет, то он автоматически создается при записи. Так как здесь записываем строку, то ее надо сначала перевести в массив байтов. И с помощью метода write строка записывается в файл.

Для автоматического закрытия файла и освобождения ресурса объект FileOutputStream создается с помощью конструктции try. catch.

При этом необязательно записывать весь массив байтов. Используя перегрузку метода write() , можно записать и одиночный байт:

Чтение файлов и класс FileInputStream

Для считывания данных из файла предназначен класс FileInputStream , который является наследником класса InputStream и поэтому реализует все его методы.

Для создания объекта FileInputStream мы можем использовать ряд конструкторов. Наиболее используемая версия конструктора в качестве параметра принимает путь к считываемому файлу:

Если файл не может быть открыт, например, по указанному пути такого файла не существует, то генерируется исключение FileNotFoundException .

Считаем данные из ранее записанного файла и выведем на консоль:

В данном случае мы считываем каждый отдельный байт в переменную i:

Когда в потоке больше нет данных для чтения, метод возвращает число -1.

Затем каждый считанный байт конвертируется в объект типа char и выводится на консоль.

Подобным образом можно считать данные в массив байтов и затем производить с ним манипуляции:

Совместим оба класса и выполним чтение из одного и запись в другой файл:

Классы FileInputStream и FileOutputStream предназначены прежде всего для записи двоичных файлов, то есть для записи и чтения байтов. И хотя они также могут использоваться для работы с текстовыми файлами, но все же для этой задачи больше подходят другие классы.

Источник

How to write to file in Java – FileOutputStream

By mkyong | Last updated: August 29, 2012

Viewed: 791,608 (+190 pv/w)

In Java, FileOutputStream is a bytes stream class that’s used to handle raw binary data. To write the data to file, you have to convert the data into bytes and save it to file. See below full example.

An updated JDK7 example, using new “try resource close” method to handle file easily.

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Читайте также:  Когда будет флеш плеер для андроид

Comments

Hi,
you are the Best, I like you very much рџ™‚

I whish you all the best.
рџ™‚

many program not run

ty 4 this useful code.

Wouldn’t that write the text all one line; even if content included a larger amount of text on different lines? I’m working in similar code and trying to write to file using text from a TextField but it put all the text on one line. Anyone know how to solve that issue?

is it possible to use relative path?

And to save in UTF8?

Thank you for this!

Hi, I want to write a result in Excel sheet row by row, can you help me please……….

Excuse me why are you closing() fop _twice_ (in both examples) ?

I stored a path to a zip file (full path) in my database and defined its data type as a text. I want to retrieve it using Java. I used the following to retrieve this zip:

Источник

Java FileOutputStream

last modified November 12, 2021

Java FileOutputStream tutorial shows how to use FileOutputStream class to write to files in Java.

Java FileOutputStream

FileOutputStream is an output stream for writing data to a File or to a FileDescriptor . FileOutputStream is a subclass of OutputStream , which accepts output bytes and sends them to some sink. In case of FileOutputStream , the sink is a file object.

Java FileOutputStream constructors

These are FileOutputStream constructors:

  • FileOutputStream(File file) — creates a file output stream to write to a File object.
  • FileOutputStream(File file, boolean append) — creates a file output stream to write to a File object; allows appending mode.
  • FileOutputStream(FileDescriptor fdObj) — creates a file output stream to write to the specified file descriptor.
  • FileOutputStream(String name) — creates a file output stream to write to the file with the specified name.
  • FileOutputStream(String name, boolean append) — creates a file output stream to write to the file with the specified name; allows appending mode.

Java FileOutputStream close

The FileOutputStream’s close method closes file output stream and releases any system resources associated with this stream. In our examples we use try-with-resources statement, which ensures that each resource is closed at the end of the statement.

Java FileOutputStream write

FileOutputStream writes bytes with the following write methods :

  • write(byte[] b) — writes array of bytes to the file output stream.
  • write(byte[] b, int off, int len) — writes len bytes from the specified byte array starting at offset off to the file output stream.
  • write(int b) — writes one byte to the file output stream.

Java FileOutputStream example

The following example uses FileOutputStream to write text to a file.

The code example writes one line to a file.

The FileOutputStream constructor takes a string as a parameter; it is the file name to which we write. We use try-with-resources construct to clean resources after we have finished writing.

FileOutputStream write bytes to the file; we get bytes from a string with the getBytes method.

The bytes are written to the file.

We show the contents of the file with the cat command.

Java FileOutputStream append to file

With FileOutputStream it is possible to append data to a file. The typical usage for appending is logging.

The code example appends text to file.

The second parameter of FileOutputStream indicates that we will append to the file.

Читайте также:  Синяя тема для android

Java FileOutputStream specifying encoding

FileWriter class, which is a Java convenience class for writing character files, has a serious limitation: it uses the default encoding and does not allow us to explicitly specify the encoding. If we have to set the encoding, we can use OutputStreamWriter and FileOutputStream .

The example writes text to a file with OutputStreamWriter . The second parameter is the charset to be used.

We show the contents of the file.

In this tutorial, we have presented the Java FileOutputStream class.

Источник

Android studio fileoutputstream to file

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter .

Constructor Summary

Constructors
Constructor and Description
FileOutputStream (File file)

Method Summary

All Methods Instance Methods Concrete Methods
Modifier and Type Method and Description
void close ()

Methods inherited from class java.io.OutputStream

Methods inherited from class java.lang.Object

Constructor Detail

FileOutputStream

First, if there is a security manager, its checkWrite method is called with name as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

FileOutputStream

First, if there is a security manager, its checkWrite method is called with name as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

FileOutputStream

First, if there is a security manager, its checkWrite method is called with the path represented by the file argument as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

FileOutputStream

First, if there is a security manager, its checkWrite method is called with the path represented by the file argument as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

FileOutputStream

First, if there is a security manager, its checkWrite method is called with the file descriptor fdObj argument as its argument.

If fdObj is null then a NullPointerException is thrown.

This constructor does not throw an exception if fdObj is invalid . However, if the methods are invoked on the resulting stream to attempt I/O on the stream, an IOException is thrown.

Method Detail

write

write

write

close

If this stream has an associated channel then the channel is closed as well.

getFD

getChannel

The initial position of the returned channel will be equal to the number of bytes written to the file so far unless this stream is in append mode, in which case it will be equal to the size of the file. Writing bytes to this stream will increment the channel’s position accordingly. Changing the channel’s position, either explicitly or by writing, will change this stream’s file position.

finalize

  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2021, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

Android studio fileoutputstream to file

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter .

Constructor Summary

Constructors

Method Summary

Constructor Description
FileOutputStream ​(File file)
All Methods Instance Methods Concrete Methods Deprecated Methods

Methods declared in class java.lang.Object

Methods declared in class java.io.OutputStream

Constructor Detail

FileOutputStream

First, if there is a security manager, its checkWrite method is called with name as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

FileOutputStream

First, if there is a security manager, its checkWrite method is called with name as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

FileOutputStream

First, if there is a security manager, its checkWrite method is called with the path represented by the file argument as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

FileOutputStream

First, if there is a security manager, its checkWrite method is called with the path represented by the file argument as its argument.

If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

FileOutputStream

First, if there is a security manager, its checkWrite method is called with the file descriptor fdObj argument as its argument.

If fdObj is null then a NullPointerException is thrown.

This constructor does not throw an exception if fdObj is invalid . However, if the methods are invoked on the resulting stream to attempt I/O on the stream, an IOException is thrown.

Method Detail

write

write

write

close

If this stream has an associated channel then the channel is closed as well.

getFD

getChannel

The initial position of the returned channel will be equal to the number of bytes written to the file so far unless this stream is in append mode, in which case it will be equal to the size of the file. Writing bytes to this stream will increment the channel’s position accordingly. Changing the channel’s position, either explicitly or by writing, will change this stream’s file position.

finalize

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2018, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Читайте также:  Motorola atrix 4g android
Оцените статью
Modifier and Type Method Description
void close ()