忍者ブログ
よくわからないことを調べて解説してみるブログ。

2024

0426
×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

2015

0620
・FileChannelは、書き込み時にByteBufferを利用できる。
・ByteBufferは、ファクトリメソッドにより生成するが、allocate,wrapの使い方に違いがある。

・allocateの場合


package june20150623;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class FileChannelByAllocated {
	public static void main(String[] args) {
		Path path = new File("test.txt").toPath();
		try (FileChannel fc = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
			ByteBuffer src = ByteBuffer.allocate(10);
			byte[] bytes = { 't', 'e', 's', 't' };
			src.put(bytes); // putのバイト入力によりpositionが進む
			src.position(0); // 進んだpositionを戻す。

			fc.write(src); // write時にpositionから書き込みされる。この仕様は、Javadoc(http://docs.oracle.com/javase/jp/7/api/java/nio/channels/WritableByteChannel.html)にも記載されている。

		} catch (IOException e) {
			e.printStackTrace();
		}

		try (FileChannel fc = FileChannel.open(path, StandardOpenOption.READ)) {
			ByteBuffer dst = ByteBuffer.allocate(10);
			fc.read(dst);

			System.out.println(new String(dst.array()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

→実行結果
test
・wrapの場合、

package june20150623;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class FileChannelByWarpped {
	public static void main(String[] args) {
		Path path = new File("test.txt").toPath();
		try (FileChannel fc = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
			byte[] bytes = { 't', 'e', 's', 't' };
			ByteBuffer src = ByteBuffer.wrap(bytes); // wrapの場合、positionは0を維持する。
			fc.write(src); // write時にpositionから書き込みされる。この仕様は、Javadoc(http://docs.oracle.com/javase/jp/7/api/java/nio/channels/WritableByteChannel.html)にも記載されている。

		} catch (IOException e) {
			e.printStackTrace();
		}

		try (FileChannel fc = FileChannel.open(path, StandardOpenOption.READ)) {
			ByteBuffer dst = ByteBuffer.allocate(10);
			fc.read(dst);

			System.out.println(new String(dst.array()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

→実行結果
test

拍手[0回]

PR
Post your Comment
Name:
Title:
Font:
Mail:
URL:
Comment:
Pass: Vodafone絵文字 i-mode絵文字 Ezweb絵文字
プロフィール
HN:
たんてーくん
性別:
非公開
フリーエリア
最新CM
[09/25 http://2017.bblbuy.com]
[09/24 http://www.japanform.com]
[09/23 http://www.japanform.com]
[09/22 http://www.japanform.com]
[09/21 http://2017.bblbuy.com]
ブログ内検索
忍者ブログ [PR]
* Template by TMP