java写文件路径(java程序运行步骤)
0x01:
FileInputStream/FileOutputStream字节流进行文件的复制
privatestaticvoidstreamCopyFile(FilesrcFile,FiledesFile){try{//使用字节流进行文件复制FileInputStreamfi=newFileInputStream(srcFile);FileOutputStreamfo=newFileOutputStream(desFile);Integerby=0;//一次读取一个字节while((by=fi.read())!=-1){fo.write(by);}fi.close();fo.close();}catch(Exceptione){e.printStackTrace();}}
0x02:
BufferedInputStream/BufferedOutputStream高效字节流进行复制文件
privatestaticvoidbufferedStreamCopyFile(FilesrcFile,FiledesFile){try{//使用缓冲字节流进行文件复制BufferedInputStreambis=newBufferedInputStream(newFileInputStream(srcFile));BufferedOutputStreambos=newBufferedOutputStream(newFileOutputStream(desFile));byte&[]b=newbyte&[1024];Integerlen=0;//一次读取1024字节的数据while((len=bis.read(b))!=-1){bos.write(b,0,len);}bis.close();bos.close();}catch(Exceptione){e.printStackTrace();}}
0x03: FileReader/FileWriter字符流进行文件复制文件
privatestaticvoidreaderWriterCopyFile(FilesrcFile,FiledesFile){try{//使用字符流进行文件复制,注意:字符流只能复制只含有汉字的文件FileReaderfr=newFileReader(srcFile);FileWriterfw=newFileWriter(desFile);Integerby=0;while((by=fr.read())!=-1){fw.write(by);}fr.close();fw.close();}catch(Exceptione){e.printStackTrace();}}
0x04:
BufferedReader/BufferedWriter高效字符流进行文件复制
privatestaticvoidbufferedReaderWriterCopyFile(FilesrcFile,FiledesFile){try{//使用带缓冲区的高效字符流进行文件复制BufferedReaderbr=newBufferedReader(newFileReader(srcFile));BufferedWriterbw=newBufferedWriter(newFileWriter(desFile));char&[]c=newchar&[1024];Integerlen=0;while((len=br.read(c))!=-1){bw.write(c,0,len);}//方式二/*Strings=null;while((s=br.readLine())!=null){bw.write(s);bw.newLine();}*/br.close();bw.close();}catch(Exceptione){e.printStackTrace();}}
0x05: NIO实现文件拷贝(用transferTo的实现 或者transferFrom的实现)
publicstaticvoidNIOCopyFile(Stringsource,Stringtarget){try{//1.采用RandomAccessFile双向通道完成,rw表示具有读写权限RandomAccessFilefromFile=newRandomAccessFile(source,"rw");FileChannelfromChannel=fromFile.getChannel();RandomAccessFiletoFile=newRandomAccessFile(target,"rw");FileChanneltoChannel=toFile.getChannel();longcount=fromChannel.size();while(count&>0){longtransferred=fromChannel.transferTo(fromChannel.position(),count,toChannel);count-=transferred;}if(fromFile!=null){fromFile.close();}if(fromChannel!=null){fromChannel.close();}}catch(Exceptione){e.printStackTrace(); }}
0x06: java.nio.file.Files.copy()实现文件拷贝,其中第三个参数决定是否覆盖
publicstaticvoidcopyFile(Stringsource,Stringtarget){PathsourcePath=Paths.get(source);PathdestinationPath=Paths.get(target);try{Files.copy(sourcePath,destinationPath,StandardCopyOption.REPLACE_EXISTING);}catch(IOExceptione){e.printStackTrace();}}