21xrx.com
2024-09-17 03:34:37 Tuesday
登录
文章检索 我的文章 写文章
Java如何实现文件复制到指定目录
2023-06-15 11:33:26 深夜i     --     --
Java 文件复制 指定目录 IO流 创建目录 输入输出流

想要在Java中实现文件复制,需要使用IO流的方式进行操作。而复制到指定目录则需要先创建目录,然后再将文件复制到该目录下。

下面是实现文件复制到指定目录的具体步骤:

1. 首先需要获取源文件和目标文件的路径。


File sourceFile = new File("C:/test/sourcefile.txt");

File targetFile = new File("C:/test/targetfile.txt");

2. 然后需要判断目标目录是否存在,如果不存在就需要创建。


File targetDir = new File("C:/test/targetdir");

if(!targetDir.exists()) {

  targetDir.mkdir();

}

3. 接着使用输入输出流将源文件复制到目标文件中。


InputStream in = new FileInputStream(sourceFile);

OutputStream out = new FileOutputStream(targetFile);

byte[] buffer = new byte[1024];

int length;

while ((length = in.read(buffer)) > 0) {

  out.write(buffer, 0, length);

}

in.close();

out.close();

通过以上步骤,我们就可以将指定目录下的文件复制到指定目录中了。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复