Java教程

Java IO操作复制文件

本文主要是介绍Java IO操作复制文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java IO操作及读写

/复制文件/
package com.XXX;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class CopyFileTest {

public static void main(String[] args) {
	File sourceFile = new File("D:\\QQPlayer_Setup_39_936.exe");
	File targetFile = new File("E:\\QQPlayer_Setup_39_936.exe");

	FileInputStream fis = null;
	FileOutputStream fos = null;

	try {
		fis = new FileInputStream(sourceFile);
		fos = new FileOutputStream(targetFile);

		byte[] buffer = new byte[1024];
		int len = 0;

		while ((len = fis.read(buffer)) != -1) {
			fos.write(buffer, 0, len);
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (fis != null) {
			try {
				fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (fos != null) {
			try {
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

}

二.

package com.XXX;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class BufferedReaderTest {
public static void main(String[] args) {

	File file = new File("E:\\li.txt");
	FileReader fr = null;
	BufferedReader br = null;

	try {
		fr = new FileReader(file);
		br = new BufferedReader(fr);

		String s = "";
		while ((s = br.readLine()) != null) {
			System.out.println(s);
		}

	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (br != null) {
			try {
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (fr != null) {
			try {
				fr.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

}

打印结果:
在这里插入图片描述

这篇关于Java IO操作复制文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!