Как писать в файл на Java - FileOutputStream
В JavaFileOutputStream - это класс потока байтов, который используется для обработки необработанных двоичных данных. Чтобы записать данные в файл, вы должны преобразовать данные в байты и сохранить их в файл. См. Полный пример ниже.
package com.example.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
FileOutputStream fop = null;
File file;
String content = "This is the text content";
try {
file = new File("c:/newfile.txt");
fop = new FileOutputStream(file);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Обновленный пример JDK7, использующий новый метод «попробуйте закрыть ресурс» для простой обработки файла.
package com.example.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
File file = new File("c:/newfile.txt");
String content = "This is the text content";
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Рекомендации
-
http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html
-
//java/how-to-read-file-in-java-fileinputstream/