よくわからないことを調べて解説してみるブログ。
2015
・FileChannelは、書き込み時にByteBufferを利用できる。
・ByteBufferは、ファクトリメソッドにより生成するが、allocate,wrapの使い方に違いがある。
・allocateの場合
→実行結果
・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
PR
Post your Comment
<<
[調べ物]よくITサイトで話題になっている色々なものの調べ。
| HOME | [JSTQB Foundation]シラバスについて忍者ブログ [PR] * Template by TMP
>>
プロフィール
HN:
たんてーくん
性別:
非公開
最新記事
(03/29)
(03/29)
(06/26)
(05/21)
(04/23)
カテゴリー
最新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]
ブログ内検索
