Skip to content

Commit 9716a9f

Browse files
committed
schemファイルが壊れる問題を修正
1 parent 3150076 commit 9716a9f

File tree

2 files changed

+20
-22
lines changed

2 files changed

+20
-22
lines changed

pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
<groupId>net.kunmc.lab</groupId>
88
<artifactId>SchemUploader</artifactId>
9-
<version>1.1-SNAPSHOT</version>
9+
<version>1.2-SNAPSHOT</version>
1010
<packaging>jar</packaging>
1111

1212
<name>SchemUploader</name>

src/main/java/net/kunmc/lab/schemuploader/FileDownloader.java

+19-21
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
import com.squareup.okhttp.Response;
66
import com.squareup.okhttp.ResponseBody;
77
import okio.BufferedSink;
8-
import okio.BufferedSource;
98
import okio.Okio;
109

10+
import java.io.ByteArrayInputStream;
1111
import java.io.File;
1212
import java.io.IOException;
1313
import java.util.Arrays;
@@ -72,27 +72,25 @@ public static Result download(File file, String url, long maxSize) {
7272
result.exceededSize = true;
7373
return result;
7474
}
75-
// ダウンロードしたファイルを保存
76-
boolean shouldDelete = false;
77-
try (BufferedSink sink = Okio.buffer(Okio.sink(file))) {
78-
sink.writeAll(body.source());
7975

80-
// Schematicファイルかどうかをチェックする
81-
if (!checkSchematic(sink.buffer())) {
82-
result.error = "Schematicファイルではありません";
83-
shouldDelete = true;
84-
return result;
85-
}
76+
// 一旦全部メモリに読み込む
77+
byte[] data = body.source().readByteArray();
8678

87-
// 結果を構築して返す
88-
result.success = true;
79+
// Schematicファイルかどうかをチェックする
80+
if (!checkSchematic(data)) {
81+
result.error = "Schematicファイルではありません";
8982
return result;
90-
} finally {
91-
// ダウンロードに失敗したらファイルを削除する
92-
if (shouldDelete) {
93-
file.delete();
94-
}
9583
}
84+
85+
// 書き込み先ファイルをオープン
86+
try (BufferedSink sink = Okio.buffer(Okio.sink(file))) {
87+
// メモリ上のデータをファイルに書き込む
88+
sink.write(data);
89+
}
90+
91+
// 結果を構築して返す
92+
result.success = true;
93+
return result;
9694
}
9795
} catch (IOException e) {
9896
result.error = String.format("IOエラー: %s", e.getMessage());
@@ -103,12 +101,12 @@ public static Result download(File file, String url, long maxSize) {
103101
/**
104102
* Schematicファイルかどうかをチェックする
105103
*
106-
* @param source ファイルのソース
104+
* @param data ファイルのソース
107105
* @return チェック結果
108106
*/
109-
private static boolean checkSchematic(BufferedSource source) {
107+
private static boolean checkSchematic(byte[] data) {
110108
// Schematicファイルかどうかをチェックする
111-
try (GZIPInputStream input = new GZIPInputStream(source.inputStream())) {
109+
try (GZIPInputStream input = new GZIPInputStream(new ByteArrayInputStream(data))) {
112110
// ヘッダーを読み込む
113111
byte[] header = new byte[12];
114112
byte[] expected = {0x0a, 0x00, 0x09, 'S', 'c', 'h', 'e', 'm', 'a', 't', 'i', 'c'};

0 commit comments

Comments
 (0)