一昨日書いていたテストコードの中で、バイト配列をファイルへ読み書きする処理がありました。
通常はデータベースへの読み書きするのですが、テストコードなので、とりあえずファイルでやろう(^^;みたいな。
で、以下のようなメソッドを書いてました。
ファイル保存
public boolean saveSnapshotFile(String filePath, byte[] snapShot){
File file = new File(filePath);
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(snapShot);
} catch (FileNotFoundException ex){
} catch(IOException ex){
}
return true;
}
ファイル読込
public byte[] readSnapshotFile(String filePath){
File file = new File(filePath);
if(!file.exists()){
return null;
}
int length = (int)file.length();
byte[] snapShot = new byte[length];
InputStream is = null;
try {
is = new FileInputStream(file);
is.read(snapShot);
} catch (FileNotFoundException ex) {
} catch(IOException ex){
}
return snapShot;
}
NIO2、NEW I/O 2って何…!?
で、昨日のデブサミでJavaセッション参加してて「NIO2」なる言葉がっ。
「New I/O 2」という新しいファイルIOなんですね。
ってか、去年参加した何らかのイベントでもこのキーワードは聞いていたはず…。
以下、詳しい情報です!
で、デブサミから帰社して以下に書き換えました。
ファイル保存(NIO2)
public boolean saveSnapshotFile(String filePath, byte[] snapShot){
FileSystem fs = FileSystems.getDefault();
Path path = fs.getPath(filePath);
try {
Files.write(path, snapShot, StandardOpenOption.CREATE_NEW);
} catch (IOException ex) {
}
return true;
}
ファイル読込(NIO2)
public byte[] readSnapshotFile(String filePath){
FileSystem fs = FileSystems.getDefault();
Path path = fs.getPath(filePath);
if(!Files.exists(path)){
return null;
}
try {
return Files.readAllBytes(path);
} catch (IOException ex) {
}
}
いけてないコードをさらしてる気もしますが…それはさておき、今後ファイル操作を書く際には、とりあえず無意識に「File」と打つ癖を治さないとなぁ、と思いました(^^;