使用java输入输出流实现文件的复制
fileutils.copyinputstreamtofile参数解释

fileutils.copyinputstreamtofile参数解释[fileutils.copyinputstreamtofile参数解释]在编程中,我们经常需要将输入流(InputStream)中的数据复制到文件中。
这个过程可能涉及到许多复杂的操作,例如流的读取、写入,文件的创建、打开和关闭等。
为了简化这个过程,许多编程语言和库提供了相应的方法或函数。
在这篇文章中,我们将重点关注Java语言的文件操作类——FileUtils中的copyInputStreamToFile方法,并深入探讨其参数的含义和使用方式。
一、copyInputStreamToFile方法简介copyInputStreamToFile方法是FileUtils类中的一个静态方法,其作用是将输入流中的数据复制到指定的文件中。
该方法的声明如下:public static void copyInputStreamToFile(InputStream source, File destination) throws IOException该方法有两个参数,分别是source和destination,分别代表输入流和目标文件。
通过调用该方法,我们可以将source中的数据复制到destination 中。
二、参数解释1. InputStream source:输入流InputStream是Java中用于处理字节流的抽象类,它是所有字节输入流的超类。
在copyInputStreamToFile方法中,source参数就是我们需要复制的输入流。
这个输入流可以来源于各种不同的地方,例如网络连接、文件读取、内存缓冲等。
在使用copyInputStreamToFile方法之前,我们需要确保source参数的有效性,也就是需要先从适当的来源获取一个InputStream实例。
2. File destination:目标文件File是Java中用于表示文件和目录路径名的类。
java实现文件的复制和删除

package myCopyDirectory;import java.io.*;import java.nio.channels.FileChannel;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Scanner;public class CopyDirectory {static int numFileDir = 0;static int numFile = 0;static long sizeDir = 0;public void initNum(){numFileDir = 0;numFile = 0;sizeDir = 0;}public void getInfoOfCopyFile(String path){File file = new File(path);if (file.exists()){SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date;if (file.isDirectory()){File[] listFile = file.listFiles();for(int i=0;i<listFile.length;i++){date = new Date(listFile[i].lastModified());System.out.print(fmt.format(date) + " ");if(listFile[i].isDirectory()){System.out.print("文件夹");System.out.println(listFile[i].toString());numFileDir++;getInfoOfCopyFile(listFile[i].toString());}else{System.out.print("文件");System.out.println(listFile[i].toString() + "(大小:" + listFile[i].length() + " Byte)");numFile++;sizeDir += listFile[i].length();}}}else{date=new Date(stModified());System.out.print(fmt.format(date)+" ");System.out.print("文件");System.out.println(file.toString() + "(大小:"+file.length() + " Byte)");numFile++;sizeDir += file.length();}}else{System.out.println("文件或文件夹不存在!");}}public void copyFiles(String sourcePath,String desPath) throws Exception{File fromFile = new File(sourcePath);if(fromFile.exists()){File desFile = new File(desPath);if(desFile.exists()){System.out.println("目录" + desPath + "目录已经存在,复制文件操作失败!");}else{if(fromFile.isFile()){File newDesFile = new File(desPath);newDesFile.createNewFile();FileInputStream inFile = new FileInputStream(fromFile);FileOutputStream outFile = new FileOutputStream(newDesFile);FileChannel inChannel = inFile.getChannel();FileChannel outChannel = outFile.getChannel();long bytesWritten = 0;long byteCount = inChannel.size();while(bytesWritten<byteCount){bytesWritten += inChannel.transferTo(bytesWritten, byteCount - bytesWritten, outChannel);}// System.out.println("文件" + fromFile.getName() + "已经成功复制到" + newDesFile.getAbsolutePath() + ".");inFile.close();outFile.close();}else{if(desFile.mkdir()){// System.out.println("目录" + desFile.getAbsolutePath() + "创建成功!");File [] info = fromFile.listFiles();for(int i=0;i<info.length;i++){String desPathTemp = desPath+"\\"+info[i].getName();copyFiles(info[i].getAbsolutePath(),desPathTemp);}}else{System.out.println("目录" + desFile.getAbsolutePath() + "创建失败!");}}}}else{System.out.println("目录" + sourcePath + "不存在,文件复制操作失败!");}}public void deleteFile (String sourcePath) throws Exception{File deleFile = new File(sourcePath);if(!deleFile.exists()){System.out.println("路径不正确.");}else {String fileName[] = deleFile.list();for (int i=0;i<fileName.length;i++){File f1 = new File(sourcePath,fileName[i]);if (f1.isFile() || f1.length()==0){f1.delete();}else if (f1.isDirectory()){// deleteFile(f1.getAbsolutePath());deleteFile(f1.getAbsolutePath());}deleFile.delete();}}}public void meun(CopyDirectory copy) throws InterruptedException,IOException,Exception {int readSelect;int choice = 1;String str;String sourcePath = null;String desPath = null;Scanner read = new Scanner(System.in);BufferedReader input = new BufferedReader(new InputStreamReader(System.in));System.out.println("欢迎使用文件删除和文件复制系统");while (choice != 0) {System.out.println("请选择您所需要的功能:");System.out.println("1 文件删除");System.out.println("2 文件复制");System.out.print("请选择:");readSelect = read.nextInt();switch(readSelect){case 1:{System.out.println("请输入目录:");sourcePath = input.readLine();System.out.println("源目录的信息如下:");System.out.println("最后修改时间属性名称");copy.getInfoOfCopyFile(sourcePath);System.out.println();System.out.println("共有" + CopyDirectory.numFileDir + "个文件夹," + CopyDirectory.numFile + "文件,总大小为" + CopyDirectory.sizeDir + "Byte。
【Java】字节流-从文件输入,输出到文件

【Java】字节流-从⽂件输⼊,输出到⽂件假如需要复制⼀张图⽚,⼀份word,⼀个rar包。
可以以字节流的⽅式,读取⽂件,然后输出到⽬标⽂件夹。
以复制⼀张4M的图⽚举例。
每次读⼀个字节:ch = (char)System.in.read(); //读⼊⼀个字符,返回读到的字节的int表⽰⽅式,读到末尾返回-1复制时候⼀个字节⼀个字节的读取、写⼊,这样是很慢的。
设置⼀个⽤来缓冲的字符数组,会让复制的过程快很多(每次读⼊的字节变多)。
⽅便阅读,类的名称⽤中⽂描述import java.io.*;public class字节流的缓冲区 {public static void main(String[] args) throws Exception {FileInputStream in=new FileInputStream("E:\\photo\\IMG.jpg");//FileOutputStream中的⽂件不存在,将⾃动新建⽂件OutputStream out=new FileOutputStream("E:\\test.jpg");byte[] buff=new byte[1024];int b;long beginTime=System.currentTimeMillis();while ((b=in.read(buff))!=-1) {out.write(buff,0,b);}long endTime=System.currentTimeMillis();System.out.println("运⾏时长为: "+(endTime-beginTime)+"毫秒");in.close();out.close();System.out.println("正常运⾏!");}}这⾥设置的字节数组是1024个字节。
4种java文件复制的方法

4种java文件复制的方法在Java中,复制文件有多种方法,这里提供四种常见的方法:1. 使用``包中的`Files`类这是Java 7及以后版本中推荐的方法,因为它使用了异步I/O操作,性能更好。
```javaimport ;public class FileCopy {public static void main(String[] args) {Path source = ("");Path target = ("");try {(source, target, _EXISTING);} catch (IOException e) {();}}}```2. 使用``包中的`FileInputStream`和`FileOutputStream`这是较旧的方法,适用于较小的文件。
对于大文件,这种方法可能效率较低,因为它一次读取整个文件。
```javaimport ;public class FileCopy {public static void main(String[] args) {File source = new File("");File target = new File("");try (FileInputStream fis = new FileInputStream(source);FileOutputStream fos = new FileOutputStream(target)) {byte[] buffer = new byte[1024];int length;while ((length = (buffer)) > 0) {(buffer, 0, length);}} catch (IOException e) {();}}}```3. 使用``包中的`FileChannel`这也是一种效率较高的方法,适用于大文件。
java pdfcopy的用法

java pdfcopy的用法PDFCopy是一个Java库,用于将一个或多个PDF文档合并为一个PDF文档。
它提供了一系列方法,用于合并、添加、删除和重排PDF文档的页面和内容。
PDFCopy的用法步骤如下:1. 导入PDFCopy库在Java项目中,首先需要导入PDFCopy库。
可以使用Maven 等构建工具来管理项目的依赖关系,将PDFCopy库添加到项目的依赖中。
2. 创建PDFCopy对象使用PDFCopy类的构造函数,创建一个PDFCopy对象。
该对象用于管理合并的PDF文档。
例如:```PDFCopy pdfCopy = new PDFCopy(new Document(), new FileOutputStream("output.pdf"));```在创建PDFCopy对象时,需要传入一个Document对象和一个输出流。
Document对象用于创建输出的PDF文档,输出流指定输出PDF的位置。
3. 打开文档在添加和合并PDF文档之前,需要调用PDFCopy的open()方法,打开文档流。
例如:```pdfCopy.open();```4. 添加PDF文档使用PDFCopy的addDocument()方法,将要合并的PDF文档添加到PDFCopy对象中。
例如:```pdfCopy.addDocument(new PdfReader("document1.pdf")); pdfCopy.addDocument(new PdfReader("document2.pdf"));```5. 关闭文档在添加完所有要合并的PDF文档后,需要调用PDFCopy的close()方法,关闭文档流。
例如:```pdfCopy.close();```6. 完成合并通过以上步骤,PDFCopy会将所有添加的PDF文档合并为一个PDF文档,并保存到指定的输出流中。
pipedinputstream使用案例

pipedinputstream使用案例pipedinputstream是Java IO中的一个类,用于创建一个连接到管道输出流的输入流。
它通常用于实现线程之间的通信,其中一个线程将数据写入管道输出流,而另一个线程从管道输入流中读取数据。
下面是一些使用pipedinputstream的案例:1. 在多线程编程中,可以使用pipedinputstream和pipedoutputstream来实现线程之间的通信。
一个线程将数据写入管道输出流,而另一个线程从管道输入流中读取数据。
2. 在网络编程中,可以使用pipedinputstream和pipedoutputstream来实现进程之间的通信。
一个进程将数据写入管道输出流,而另一个进程从管道输入流中读取数据。
3. 在文件复制中,可以使用pipedinputstream和pipedoutputstream来实现文件的快速复制。
一个线程从文件读取数据并写入管道输出流,而另一个线程从管道输入流中读取数据并写入文件。
4. 在数据加密和解密中,可以使用pipedinputstream和pipedoutputstream来实现数据的加密和解密。
一个线程将数据加密并写入管道输出流,而另一个线程从管道输入流中读取数据并解密。
5. 在音频和视频播放中,可以使用pipedinputstream和pipedoutputstream来实现音频和视频的实时传输。
一个线程将音频或视频数据写入管道输出流,而另一个线程从管道输入流中读取数据并播放。
6. 在图像处理中,可以使用pipedinputstream和pipedoutputstream来传输图像数据。
一个线程将图像数据写入管道输出流,而另一个线程从管道输入流中读取数据并处理图像。
7. 在数据分析和处理中,可以使用pipedinputstream和pipedoutputstream来传输数据。
一个线程将数据写入管道输出流,而另一个线程从管道输入流中读取数据并进行分析和处理。
基于Java文件输入输出流实现文件上传下载功能

基于Java⽂件输⼊输出流实现⽂件上传下载功能本⽂为⼤家分享了Java实现⽂件上传下载功能的具体代码,供⼤家参考,具体内容如下前端通过form表单的enctype属性,将数据传递⽅式修改为⼆进制”流“的形式,服务端(servlet)通过 getInputStream() 获取流信息,运⽤java I/O 流的基础操作将流写⼊到⼀个服务端临时创建的⽂件temp中,然后再次利⽤⽂件基本操作,读取并截取临时⽂件内容,根据其中信息创建相应的⽂件,将读取出来的具体信息写⼊,下载时,根据提交的⽂件名称,找到服务器端相应的⽂件,然后根据输出流outStream输出到页⾯,同时将servlet的响应类型和响应头进⾏设置。
具体传输流程如下图:流信息的部分为:具体代码如下:前端代码:<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><script src="Js/jquery.js"></script></head><body><form action="FileUpServlet" method="post" enctype="multipart/form-data"><table><tr><td>请选择上传⽂件:</td><td><input id="myfile" name="myfile" type="file" value="" /></td><td><input type="submit" value="上传"></td></tr><tr><td>${info}</td></tr></table></form>⽂件下载:<a href="FileLoadownServlet?filename=${filename}">${filename}</a></body></html>上传servlet部分(核⼼)@WebServlet("/FileUpServlet")public class FileUpServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public FileUpServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stubdoPost(request, response);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stubrequest.setCharacterEncoding("utf-8");InputStream filesource = request.getInputStream();//request获取流信息String tempname = "D:/temp";//tempfile代表临时存放⽂件File tempfile = new File(tempname);//创建临时⽂件FileOutputStream outputStream = new FileOutputStream(tempfile);//输出流对象,指定输出指tempfile⽬录下byte b[] = new byte[1024];int n;while((n = filesource.read(b))!= -1)//从输出流中每次读取1024字节,直⾄读完{outputStream.write(b,0,n);}outputStream.close();filesource.close();//关闭输⼊输出流/*以下为具体的⽂件操作,主要为解析临时产⽣的 temp⽂件,知识多为java输⼊输出流的内容!*/RandomAccessFile randomfile = new RandomAccessFile(tempfile, "r");//随机流,指定要读临时⽂件,只读randomfile.readLine();//读取第⼀⾏,⽆效数据,不需要String str = randomfile.readLine();//读取第⼆⾏int beginIndex = stIndexOf("=")+2;//指定所需数据的开始位置int endIndex = stIndexOf("\"");//指定所需数据截⾄位置String filename = str.substring(beginIndex,endIndex);//截取⽂件名//重新定位⽂件指针,获取⽂件内容randomfile.seek(0);//⽂件指针从头开始long startext = 0;int i = 1;//⽂件内容开始位置while((n=randomfile.readByte()) != -1&&i <= 4){if(n=='\n'){startext = randomfile.getFilePointer();i++;}}startext = randomfile.getFilePointer() - 1;//获取⽂件内容结束位置randomfile.seek(randomfile.length());long endtext = randomfile.getFilePointer();int j = 1;while(endtext >= 0 && j <= 2){endtext--;randomfile.seek(endtext);if(randomfile.readByte()=='\n'){j++;}}endtext = endtext-1;//将临时⽂件保存⾄指定⽬录中String realpath = getServletContext().getRealPath("/")+"images";//设置⽂件保存⽬录System.out.println(realpath);File fileupload = new File(realpath);if(!fileupload.exists()){fileupload.mkdir();//⽬录不存在则创建}File savefile = new File(realpath,filename);RandomAccessFile randomAccessFile = new RandomAccessFile(savefile, "rw");randomfile.seek(startext);while(startext<endtext){randomAccessFile.write(randomfile.readByte());//⽂件写⼊startext = randomfile.getFilePointer();}//关闭各种输⼊输出流randomAccessFile.close();randomfile.close();tempfile.delete();//删除临时⽂件SimpleDateFormat timed = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date nowdate = new Date();String time = timed.format(nowdate.getTime());request.setAttribute("info", time+" "+filename+"上传成功!");request.setAttribute("filename", filename);request.getRequestDispatcher("/fildeOp.jsp").forward(request, response);}}下载部分protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stubString filename = request.getParameter("filename");String path = getServletContext().getRealPath("/")+"images/";File file = new File(path+filename);//找到⽂件if(file.exists())response.setContentType("application/x-msdownload"); //设置响应类型,此处为下载类型response.setHeader("Content-Disposition", "attachment;filename=\""+filename+"\"");//以附件的形式打开 InputStream inputStream = new FileInputStream(file);ServletOutputStream outputStream = response.getOutputStream();byte b[] = new byte[1024];int n;while((n = inputStream.read(b)) != -1){outputStream.write(b,0,n);}outputStream.close();inputStream.close();}else{request.setAttribute("result", "⽂件不存在!下载失败!");request.getRequestDispatcher("/fildeOp.jsp").forward(request, response);}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
Java 复制文件

String fileName=fileChooser.getSelectedFile().getAbsolutePath();
if (event.getSource().equals(selectFile1)){//判断事件来自于哪个按钮
jtfSourceFile.setText(fileName);//设置源文件路径
java.io.File fileOut=new java.io.File(file2);//用路径名生成目标文件
FileInputStream fin=new FileInputStream(fileIn);//得到文件输入流
FileOutputStream fout=new FileOutputStream(fileOut);//得到文件输出流
panel.add(new JLabel("源文件"));//增加组件到面板(panel)上
panel.add(jtfSourceFile);
panel.add(selectFile1);
box.add(panel);//增加组件到Box上
panel=new JPanel();
panel.add(new JLabel("目标文件"));
String sourceFile=jtfSourceFile.getText();//得到源文件路径
String targetFile=jtfTargetFile.getText();//得到目标文件路径
if (copy(sourceFile,targetFile)){//拷贝文件
//显示拷贝成功信息
fout.close();//关闭输出流
return true;