java io使用字节流,转换流,缓冲流组合较高效率的完成任意类型的文件的复制

直接贴代码:

1、main方法:

 public static void main(String[] args) throws IOException {
	        String srcDirName = "D:\\testSrcFile\\testFile.test";
	        String destDirName = "D:\\testDestFile";
	        String destFileName = "testFIle.dest";
			File 	srcFIle = 	new File(srcDirName );
			File destDir = new File(destDirName );
			if(!destFIle.exists()){
				destFile.mkdirs();
			}
			File destFile = new File(destDirName+"\\"+destFileName);
					copyFIle(srcFIle,destFile);
			}
		}

2、复制文件的业务方法

 private static void copyFile(File sFile, File destFile) throws IOException {

        try (
        	
        	 FileInputStream fis = new FileInputStream(sFile);
             FileOutputStream fos = new FileOutputStream(destFile);
             //指定以什么编码格式解析,参数需要的是字节输入流
             InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
			//指定以什么编码格式写入,参数需要的是字节输出流
             OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
             BufferedReader br = new BufferedReader(isr);
             BufferedWriter bw = new BufferedWriter(osw);
        ){

            String mm = br.readLine();
            while(mm!=null){
                bw.write(mm);
                //写入行分隔符
                bw.newLine();
                System.out.println("mm="+mm);
                mm = br.readLine();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(java,io,后端)