gpt4 book ai didi

java - 在java中以编程方式创建tar文件

转载 作者:行者123 更新时间:2023-12-01 06:15:04 25 4
gpt4 key购买 nike

我正在尝试使用 Java 的 JTar 将目录转换为 tar 文件,其中包括一个空子目录和带有一些 .json 文件的子目录。包含文件的文件夹会自动包含在 .tar 文件中,但空文件夹则不会。我想使用所有(空和数据初始化)子目录创建 .tar 文件。我的代码是这样的:

try
{
File tarFile = new File("somefilename.tar");
TarOutputStream tos = new TarOutputStream(new FileOutputStream(tarFile));

tartar("directoryname", tos);
tos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
private static void tartar(String dir, TarOutputStream tos)
{
File f = new File(dir);
String[] flist = f.list();
int buffersize = 1024;
byte[] buf = new byte[buffersize];
for (int i = 0; i < flist.length; i++)
{
File f2 = new File(f, flist[i]);
if (f2.isDirectory())
{
tartar(f2.getPath(), tos);
continue;
}
try
{
FileInputStream fis = new FileInputStream(f2);
// TarEntry te = new TarEntry(f2.getPath());
TarEntry te = new TarEntry(f2, f2.getPath());
tos.putNextEntry(te);
int count = 0;
while ((count = fis.read(buf, 0, buffersize)) != -1)
{
tos.write(buf, 0, count);
}
// tos.closeEntry();
// tos.close();
fis.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

}

最佳答案

虽然我没有在 Java 中调用 tarball,但在 Linux 中,您可以使用 Runtime、Process 和 ProcessBuilder API 运行命令“tar -cvzf file_name.tar.gz directory_name/”。

关于java - 在java中以编程方式创建tar文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26883844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com