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 }
重点看红色部分,底层还是字节流,没具体看,可能效率上会更高。
能自己写的就别用人家封装好的,即使用了,也要分析人家的实现方式!