1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ファイルの読み書き

Posted at

ファイルに2進数のデータを追記する

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
	public static void main(String[] args) throws IOException {
		//ファイル/パスを指定して生成
		FileOutputStream fos = new FileOutputStream("bainary.data", true);
		//書き込むデータをバッファに保存
		fos.write(65);
		fos.flush();
		//ファイルを閉じる
		fos.close();
	}
}

書き込み

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
	public static void main(String[] args) throws IOException {
		FileWriter fw = new FileWriter("xxxx", true);
		fw.write("A");
		fw.flush();
		fw.close();
	}
}

読み取り

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
	public static void main(String[] args) throws IOException {
		FileReader fw = new FileReader("xxx.data");
		int i = fw.read();
		while (i != 1) {
			char c = (char) i;
			{
				System.out.println(c);
				i = fw.read();
			}
			fw.close();
		}
	}
}

例外処理

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
	public static void main(String[] args) throws IOException {
		FileWriter fw = null;
		try {
			fw = new FileWriter("xxxx.data", true);
			fw.write("A");
			fw.flush();
			//例外の詳細情報をeに渡し、例外処理を行う
		} catch (IOException e) {
			System.out.println("異常が発生しました");
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e2) {
				}
			}
		}
	}
}

try with resources文の利用

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
	public static void main(String[] args) {
		try (FileWriter fw = new FileWriter("xxxx.data", true);) {
			fw.write("A");
			fw.flush();
			// 例外の詳細情報をeに渡し、例外処理を行う
		} catch (IOException e) {
			System.out.println("異常が発生しました");
		}
	}

}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?