Прямо сейчас я борюсь с файлами, потоками, буферами чтения и записи.
Итак, у меня есть zipFile, содержащий XML-файл. Моя цель — восстановить информацию XML в строку.
Прямо сейчас мой код выглядит так:
byte[] buffer = new byte[2048];
String outpath = "";
// open the zip file stream
try(InputStream theFile = new FileInputStream(TEST_ZIP);
ZipInputStream stream = new ZipInputStream(theFile)){
ZipEntry entry;
while((entry = stream.getNextEntry())!=null) {
// Once we get the entry from the stream, the stream is
// positioned read to read the raw data, and we keep
// reading until read returns 0 or less.
outpath = DOSSIER + "/" + entry.getName();
try (FileOutputStream output = new FileOutputStream(outpath)) {
int len = 0;
while ((len = stream.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
}
}
}
var file = new File(outpath);
String content = getContentFromFile(file);
file.delete();
Метод getCONtentFromFile следующий:
private static String getContentFromFile(File file) {
String content = new String();
if (file.exists()) {
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String linea;
while ((linea = bufferedReader.readLine()) != null) {
content = content + linea;
}
} catch (IOException e) {
System.out.println("Erreur lors de la lecture du fichier." + e.getMessage());
}
} else {
System.out.println("Le fichier n'existe pas.");
}
return content;
}
Код работает, но мне интересно, есть ли более простой/лучший способ сделать это извлечение.
Кроме того, входной поток указывает, что он достиг EOF, возвращая -1 из read, а не 0.




Кажется, это много дополнительной работы. Ваш вопрос подразумевает, что в zip-файле есть только одна запись, поэтому вы можете просто прочитать эту запись напрямую:
byte[] bytes;
try (ZipFile zipFile = new ZipFile(TEST_ZIP);
InputStream stream = zipFile.getInputStream(
zipFile.stream().findFirst().orElseThrow())) {
bytes = stream.readAllBytes();
}
String content = new String(bytes, StandardCharsets.UTF_8);
Не нужно записывать байты в отдельный файл.
Обратите внимание, что нет смысла копировать запись ZIP в файл, а затем читать его. Вы можете просто прочитать строку из записи ZIP напрямую. Кроме того, если вы знаете имя записи XML, рассмотрите возможность использования ZipFile , чтобы вы могли просто получить
ZipEntryнапрямую. АльтернативойZipFileявляется Поставщик файловой системы ZIP (который позволит вам использоватьFiles.readString(...)).