Javaでファイルに書き込む方法 – FileOutputStream
Javaでは、http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FileOutputStream.html[FileOutputStream]は、生のバイナリ・データを処理するために使用されるバイト・ストリーム・クラスです。データをファイルに書き込むには、データをバイトに変換してファイルに保存する必要があります。以下の完全な例を参照してください。
package com.mkyong.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(); } } } }
新しい “try resource close”メソッドを使用して、ファイルを簡単に処理する、更新されたJDK7の例。
package com.mkyong.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/