gpt4 book ai didi

Java方法将文件放入文件夹中(均作为参数)

转载 作者:太空宇宙 更新时间:2023-11-04 15:11:39 24 4
gpt4 key购买 nike

我一直在搜索这个论坛和许多其他资源,试图找到我的 Java 难题的答案,但没有结果,而且我无法使用 Apache commons。

我在尝试将文件放入特定文件夹时遇到了困难;该文件夹已使用 .mkdir() 创建:

public void createRepositoryDir(String pRepositoryName)
{
File repositoryDir = new File(pRepositoryName);
repositoryDir.mkdir();
}

使用 JFileChooser 选择文件并作为 File 对象返回,但我发现很难将该文件放入目录 (repositoryDir.mkdir();)。

我需要将目录位置和文件位置作为参数传递,因为我使用的是基于菜单的系统。

我已经尝试过:

File file = new File(dir, pFile);

但这似乎又是文件类型和字符串类型之间的冲突。

如有任何建议,我们将不胜感激!

最佳答案

假设 pFile 是您的源文件,dir 是您的目标目录,您将需要创建一个新的目标文件:

File targetFile = new File(dir, pFile.getName());

然后,需要将pFile的内容复制到targetFile中。您可以通过多种不同的方式来完成此操作,但这里是一种(为了清楚起见,省略了异常处理):

FileInputStream fis = new FileInputStream(pFile);
FileOutputStream fos = new FileOutputStream(targetFile);
copyStream(fis, fos, 10000);
fos.flush();
fos.close();
fis.close();

其中 copyStream 方法定义为:

public static void copyStream(final InputStream inputStream, final OutputStream outputStream, final int bufferLength) throws IOException {
// copy the input stream to the output stream
byte[] buf = new byte[bufferLength];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
}

关于Java方法将文件放入文件夹中(均作为参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21269796/

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