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 3 years have passed since last update.

一時ファイルを作成して、圧縮して、なんらかの処理をして、削除する実装

Posted at

Javaにおける一時ファイルの作成やzip圧縮の実装方法について調べたので、整理を目的として記事を書く。「なんらかの処理」は、どこかにアップロードするなどを想定していた。

Sample.java
// 一時ファイルを作成
File tmpFile = File.createTempFile("tmpSqlFile", ".txt");
		
// データ書込み
writeDate(tmpFile);
		
// 圧縮
compress(tmpFile);
		
// なんらかの処理
		
// ファイル削除
deleteFile(tmpFile);
deleteFile(new File(getZipPath(tmpFile)));

File.createTempFile("tmpSqlFile", ".txt")ということで、SQLの記述されたテキストファイルを想定していた。

Sample.java
private static void writeDate(File f) throws IOException {

	// FileWriterクラス作成
	FileWriter fw = new FileWriter(f);
		
	// 書込み
	getList().stream().forEach(s -> {		
		try {
			fw.write(s + ";\r\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	});
		
	// ファイルを閉じる
	fw.close();
}
Sample.java
private static List<String> getList() {
		
	// データ準備
	List<String> arr = new ArrayList<>();
	arr.add("UPDATE uesrs SET name = 'newName1' WHERE id = 0001;");
	arr.add("UPDATE uesrs SET name = 'newName2' WHERE id = 0002;");

	Map<String, List<String>> map = new HashMap<>();
	map.put("users", arr);
		
	// SQL抽出
	List<String> sqlList = new ArrayList<>();
		
	map.values().stream().forEach(a -> {
		a.stream().forEach(sql -> sqlList.add(sql));
	});
		
	return sqlList;	
}

テーブル名をキーとし、値がそのテーブルのUPDATE文のリストであるようなMapがデータとして生成されている、というパターンを考えていた。上記は1テーブルに対してだけど、複数テーブルも考慮してforEachがネストされた実装となっている。

Sample.java
private static void compress(File f) throws IOException {
		
	ZipOutputStream zos = 
			new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(getZipPath(f))));
	ZipEntry entry = new ZipEntry(f.getName());
	zos.putNextEntry(entry);
	InputStream is = new BufferedInputStream(new FileInputStream(f));
		
	int len = 0;
	byte[] buf = new byte[1024];
	while ((len = is.read(buf)) != -1) {
		zos.write(buf, 0, len);
	}
		
	zos.close();
	is.close();
}

引数のFileオブジェクトをzip圧縮するのみ(複数ファイルをzip圧縮するわけではない)。

Sample.java
private static String getZipPath(File f) {
	return f.getParent() + "\\hoge.zip"; 
}

一時ファイルを作成した同階層にzipファイルも生成する。

Sample.java
private static void deleteFile(File f) {
	if (f != null && f.exists()) {
		f.delete();
	}
}

上述した実装を参考にして実装する場面があって、再度見直すと改善点もありそう。そもそもの一時ファイルを作成する必要性などについては、また考えられたら。

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?