2018年1月31日 10:42:55
工作完写点博客记录下。
需求:从web-inf下拷贝文件到指定目录。
目录结构
直接贴代码
第一种方式,字节流读取
try { int index = 0;
System.out.println("开始读取"); File filef = new File("web/WEB-INF/apk/"+channel+".apk");
System.out.println(filef.getAbsolutePath()); InputStream inputStream = new FileInputStream(filef.getAbsolutePath());//获取文件所在路径并读入
if(inputStream!=null){
//读取文件(缓存字节流)
BufferedInputStream in = new BufferedInputStream(inputStream);
//写入相应的文件
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("web/apk/"+channel+".apk"));
//读取数据
//一次性取多少字节
byte[] bytes = new byte[2048];
//接受读取的内容
int n = -1;
//循环取出数据
while ((n = in.read(bytes,0,bytes.length)) != -1) {
//转换成字符串
String str = new String(bytes,0,n,"GBK");
System.out.println(str);
//写入相关文件
out.write(bytes, 0, n);
}
//清除缓存
out.flush();
//关闭流
in.close();
out.close();
}else if(index<=1){ index++;
} //}
/*}*/
} catch (Exception e) {
e.printStackTrace();
}
注意读取的文件路径要从web开始写!
第二种方式
使用apache的commons的FileUtils
jar:commons-io-2.4.jar
使用方式
@Test
public void test2(){
File file2 = new File("web/apk/22.apk");
File file1 = new File("web/WEB-INF/apk/22.apk");
System.out.println(file1.getAbsolutePath());
try {
FileUtils.copyFile(file1,file2);
} catch (IOException e) {
e.printStackTrace();
}
}
file1是要读取的路径,file2是要写入的路径
贴一下人家工具类的源码
/**
* Copies a file to a new location.
* <p>
* This method copies the contents of the specified source file
* to the specified destination file.
* The directory holding the destination file is created if it does not exist.
* If the destination file exists, then this method will overwrite it.
* <p>
* <strong>Note:</strong> Setting <code>preserveFileDate</code> to
* {@code true} tries to preserve the file's last modified
* date/times using {@link File#setLastModified(long)}, however it is
* not guaranteed that the operation will succeed.
* If the modification operation fails, no indication is provided.
*
* @param srcFile an existing file to copy, must not be {@code null}
* @param destFile the new file, must not be {@code null}
* @param preserveFileDate true if the file date of the copy
* should be the same as the original
*
* @throws NullPointerException if source or destination is {@code null}
* @throws IOException if source or destination is invalid
* @throws IOException if an IO error occurs during copying
* @throws IOException if the output file length is not the same as the input file length after the copy
* completes
* @see #copyFileToDirectory(File, File, boolean)
* @see #doCopyFile(File, File, boolean)
*/
public static void copyFile(final File srcFile, final File destFile,
final boolean preserveFileDate) throws IOException {
checkFileRequirements(srcFile, destFile);
if (srcFile.isDirectory()) {
throw new IOException("Source '" + srcFile + "' exists but is a directory");
}
if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
}
final File parentFile = destFile.getParentFile();
if (parentFile != null) {
if (!parentFile.mkdirs() && !parentFile.isDirectory()) {
throw new IOException("Destination '" + parentFile + "' directory cannot be created");
}
}
if (destFile.exists() && destFile.canWrite() == false) {
throw new IOException("Destination '" + destFile + "' exists but is read-only");
}
doCopyFile(srcFile, destFile, preserveFileDate);
}
/**
* Internal copy file method.
* This caches the original file length, and throws an IOException
* if the output file length is different from the current input file length.
* So it may fail if the file changes size.
* It may also fail with "IllegalArgumentException: Negative size" if the input file is truncated part way
* through copying the data and the new file size is less than the current position.
*
* @param srcFile the validated source file, must not be {@code null}
* @param destFile the validated destination file, must not be {@code null}
* @param preserveFileDate whether to preserve the file date
* @throws IOException if an error occurs
* @throws IOException if the output file length is not the same as the input file length after the
* copy completes
* @throws IllegalArgumentException "Negative size" if the file is truncated so that the size is less than the
* position
*/
private static void doCopyFile(final File srcFile, final File destFile, final boolean preserveFileDate)
throws IOException {
if (destFile.exists() && destFile.isDirectory()) {
throw new IOException("Destination '" + destFile + "' exists but is a directory");
} try (FileInputStream fis = new FileInputStream(srcFile);
25 FileChannel input = fis.getChannel();
26 FileOutputStream fos = new FileOutputStream(destFile);
27 FileChannel output = fos.getChannel()) {
final long size = input.size(); // TODO See IO-386
long pos = 0;
long count = 0;
while (pos < size) {
final long remain = size - pos;
count = remain > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : remain;
final long bytesCopied = output.transferFrom(input, pos, count);
if (bytesCopied == 0) { // IO-385 - can happen if file is truncated after caching the size
break; // ensure we don't loop forever
}
pos += bytesCopied;
}
} final long srcLen = srcFile.length(); // TODO See IO-386
final long dstLen = destFile.length(); // TODO See IO-386
if (srcLen != dstLen) {
throw new IOException("Failed to copy full contents from '" +
srcFile + "' to '" + destFile + "' Expected length: " + srcLen + " Actual: " + dstLen);
}
if (preserveFileDate) {
destFile.setLastModified(srcFile.lastModified());
}
}
重点看红色部分,底层还是字节流,没具体看,可能效率上会更高。
能自己写的就别用人家封装好的,即使用了,也要分析人家的实现方式!