WEB-INF目录下文件复制的几种方式

本文介绍两种Java文件复制的方法:一种是通过字节流读取和写入的方式;另一种是利用Apache Commons IO库中的FileUtils工具类。同时展示了具体的代码实现,并分析了工具类内部的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2018年1月31日 10:42:55

工作完写点博客记录下。

需求:从web-inf下拷贝文件到指定目录。

目录结构

直接贴代码

第一种方式,字节流读取

 1 try { 
 2 
 3            
 4                  
 5                   int index = 0;
 6                   System.out.println("开始读取");
 7             
 8             File filef = new File("web/WEB-INF/apk/"+channel+".apk");
 9             System.out.println(filef.getAbsolutePath());
10 
11             InputStream inputStream = new FileInputStream(filef.getAbsolutePath());//获取文件所在路径并读入
12                   if(inputStream!=null){
13                       //读取文件(缓存字节流)
14                       BufferedInputStream in = new BufferedInputStream(inputStream);
15                       //写入相应的文件
16                       BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("web/apk/"+channel+".apk"));
17                       //读取数据
18                       //一次性取多少字节
19                       byte[] bytes = new byte[2048];
20                       //接受读取的内容
21                       int n = -1;
22                       //循环取出数据
23                       while ((n = in.read(bytes,0,bytes.length)) != -1) {
24                           //转换成字符串
25                           String str = new String(bytes,0,n,"GBK");
26                           System.out.println(str);
27                           //写入相关文件
28                           out.write(bytes, 0, n);
29                       }
30                       //清除缓存
31                       out.flush();
32                       //关闭流
33                       in.close();
34                       out.close();
35                   }else if(index<=1){
36                      
42                       index++;
43                   }
44 
45                  //}
46             /*}*/
47         } catch (Exception e) {
48             e.printStackTrace();
49         }

注意读取的文件路径要从web开始写!

第二种方式

  使用apache的commons的FileUtils

  jar:commons-io-2.4.jar

使用方式

 

 1 @Test
 2     public void test2(){
 3         File file2 = new File("web/apk/22.apk");
 4         File file1 = new File("web/WEB-INF/apk/22.apk");
 5         System.out.println(file1.getAbsolutePath());
 6         try {
 7             FileUtils.copyFile(file1,file2);
 8         } catch (IOException e) {
 9             e.printStackTrace();
10         }
11     }

 

file1是要读取的路径,file2是要写入的路径

贴一下人家工具类的源码

 1 /**
 2      * Copies a file to a new location.
 3      * <p>
 4      * This method copies the contents of the specified source file
 5      * to the specified destination file.
 6      * The directory holding the destination file is created if it does not exist.
 7      * If the destination file exists, then this method will overwrite it.
 8      * <p>
 9      * <strong>Note:</strong> Setting <code>preserveFileDate</code> to
10      * {@code true} tries to preserve the file's last modified
11      * date/times using {@link File#setLastModified(long)}, however it is
12      * not guaranteed that the operation will succeed.
13      * If the modification operation fails, no indication is provided.
14      *
15      * @param srcFile          an existing file to copy, must not be {@code null}
16      * @param destFile         the new file, must not be {@code null}
17      * @param preserveFileDate true if the file date of the copy
18      *                         should be the same as the original
19      *
20      * @throws NullPointerException if source or destination is {@code null}
21      * @throws IOException          if source or destination is invalid
22      * @throws IOException          if an IO error occurs during copying
23      * @throws IOException          if the output file length is not the same as the input file length after the copy
24      * completes
25      * @see #copyFileToDirectory(File, File, boolean)
26      * @see #doCopyFile(File, File, boolean)
27      */
28     public static void copyFile(final File srcFile, final File destFile,
29                                 final boolean preserveFileDate) throws IOException {
30         checkFileRequirements(srcFile, destFile);
31         if (srcFile.isDirectory()) {
32             throw new IOException("Source '" + srcFile + "' exists but is a directory");
33         }
34         if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
35             throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
36         }
37         final File parentFile = destFile.getParentFile();
38         if (parentFile != null) {
39             if (!parentFile.mkdirs() && !parentFile.isDirectory()) {
40                 throw new IOException("Destination '" + parentFile + "' directory cannot be created");
41             }
42         }
43         if (destFile.exists() && destFile.canWrite() == false) {
44             throw new IOException("Destination '" + destFile + "' exists but is read-only");
45         }
46         doCopyFile(srcFile, destFile, preserveFileDate);
47     }
 1 /**
 2      * Internal copy file method.
 3      * This caches the original file length, and throws an IOException
 4      * if the output file length is different from the current input file length.
 5      * So it may fail if the file changes size.
 6      * It may also fail with "IllegalArgumentException: Negative size" if the input file is truncated part way
 7      * through copying the data and the new file size is less than the current position.
 8      *
 9      * @param srcFile          the validated source file, must not be {@code null}
10      * @param destFile         the validated destination file, must not be {@code null}
11      * @param preserveFileDate whether to preserve the file date
12      * @throws IOException              if an error occurs
13      * @throws IOException              if the output file length is not the same as the input file length after the
14      * copy completes
15      * @throws IllegalArgumentException "Negative size" if the file is truncated so that the size is less than the
16      * position
17      */
18     private static void doCopyFile(final File srcFile, final File destFile, final boolean preserveFileDate)
19             throws IOException {
20         if (destFile.exists() && destFile.isDirectory()) {
21             throw new IOException("Destination '" + destFile + "' exists but is a directory");
22         }
23 
24         try (FileInputStream fis = new FileInputStream(srcFile);
25              FileChannel input = fis.getChannel();
26              FileOutputStream fos = new FileOutputStream(destFile);
27              FileChannel output = fos.getChannel()) {
28             final long size = input.size(); // TODO See IO-386
29             long pos = 0;
30             long count = 0;
31             while (pos < size) {
32                 final long remain = size - pos;
33                 count = remain > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : remain;
34                 final long bytesCopied = output.transferFrom(input, pos, count);
35                 if (bytesCopied == 0) { // IO-385 - can happen if file is truncated after caching the size
36                     break; // ensure we don't loop forever
37                 }
38                 pos += bytesCopied;
39             }
40         }
41 
42         final long srcLen = srcFile.length(); // TODO See IO-386
43         final long dstLen = destFile.length(); // TODO See IO-386
44         if (srcLen != dstLen) {
45             throw new IOException("Failed to copy full contents from '" +
46                     srcFile + "' to '" + destFile + "' Expected length: " + srcLen + " Actual: " + dstLen);
47         }
48         if (preserveFileDate) {
49             destFile.setLastModified(srcFile.lastModified());
50         }
51     }

重点看红色部分,底层还是字节流,没具体看,可能效率上会更高。

能自己写的就别用人家封装好的,即使用了,也要分析人家的实现方式!

 

转载于:https://www.cnblogs.com/find-the-right-direction/p/8391179.html

工件构建器: Error: Couldn't copy [D:\java chengxu\daer xia\JDBC_web\web\WEB-INF\lib\standard.jar] to [D:\java chengxu\daer xia\JDBC_web\out\artifacts\JDBC_web_war_exploded\WEB-INF\lib\standard.jar] java.io.IOException: Couldn't copy [D:\java chengxu\daer xia\JDBC_web\web\WEB-INF\lib\standard.jar] to [D:\java chengxu\daer xia\JDBC_web\out\artifacts\JDBC_web_war_exploded\WEB-INF\lib\standard.jar] at com.intellij.openapi.util.io.FileUtil.performCopy(FileUtil.java:412) at com.intellij.openapi.util.io.FileUtil.copyContent(FileUtil.java:401) at org.jetbrains.jps.incremental.FSOperations.copy(FSOperations.java:490) at org.jetbrains.jps.incremental.artifacts.instructions.FilterCopyHandler.copyFile(FilterCopyHandler.java:27) at org.jetbrains.jps.incremental.artifacts.instructions.FileBasedArtifactRootDescriptor.copyFromRoot(FileBasedArtifactRootDescriptor.java:89) at org.jetbrains.jps.incremental.artifacts.IncArtifactBuilder$IncArtifactBuilderHelper.processFiles(IncArtifactBuilder.java:236) at org.jetbrains.jps.incremental.artifacts.IncArtifactBuilder$IncArtifactBuilderHelper.build(IncArtifactBuilder.java:95) at org.jetbrains.jps.incremental.artifacts.IncArtifactBuilder.build(IncArtifactBuilder.java:50) at org.jetbrains.jps.incremental.artifacts.IncArtifactBuilder.build(IncArtifactBuilder.java:36) at org.jetbrains.jps.incremental.IncProjectBuilder.buildTarget(IncProjectBuilder.java:1314) at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk(IncProjectBuilder.java:608) at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk(IncProjectBuilder.java:1573) at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected(IncProjectBuilder.java:1287) at org.jetbrains.jps.incremental.IncProjectBuilder$BuildParallelizer$1.run(IncProjectBuilder.java:1249) at com.intellij.util.concurrency.BoundedTaskExecutor.doRun(BoundedTaskExecutor.java:249) at com.intellij.util.concurrency.BoundedTaskExecutor.access$200(BoundedTaskExecutor.java:30) at com.intellij.util.concurrency.BoundedTaskExecutor$1.executeFirstTaskAndHelpQueue(BoundedTaskExecutor.java:227) at com.intellij.util.ConcurrencyUtil.runUnderThreadName(ConcurrencyUtil.java:218) at com.intellij.util.concurrency.BoundedTaskExecutor$1.run(BoundedTaskExecutor.java:212) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) at java.base/java.lang.Thread.run(Thread.java:833) Caused by: java.nio.file.AccessDeniedException: D:\java chengxu\daer xia\JDBC_web\out\artifacts\JDBC_web_war_exploded\WEB-INF\lib\standard.jar at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108) at java.base/sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:236) at java.base/java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:484) at java.base/java.nio.file.Files.newOutputStream(Files.java:228) at com.intellij.openapi.util.io.FileUtil.openOutputStream(FileUtil.java:445) at com.intellij.openapi.util.io.FileUtil.performCopy(FileUtil.java:408) ... 21 more
最新发布
06-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值