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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至624739273@qq.com举报,一经查实,本站将立刻删除。
Like (0)
柳的头像

相关推荐

发表回复

Please Login to Comment
微信
微信
SHARE
TOP
要想花得少,就用购宝。话费电费9折起,官方公众号:购宝