JAVA 文件操作(3)

JAVA 文件操作(3)

要求:

  • 通过二进制流的操作方式把程序调整为可以实现对任何类型文件进行文件复制(而不是调用windows命令行的内部命令copy)。

主要方法:

1. createNewFile()

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

Returns:

true if the named file does not exist and was successfully created; false if the named file already exists

2.FileInputStream

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

FileInputStream(File file) :Creates a FileInputStream by opening a connection to an actual file,the file named by the File object file in the file system.

3. FileOutputStream

A file output stream is an output stream for writing data to a File or to a FileDescriptor.

FileOutputStream(File file) : Creates a file output stream to write to the file represented by the specified File object.

程序:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
public class CopyDemo {
	public static void main(String args[]) throws IOException {
		try {
			File file_1 = new File("E:\\年少有为.txt"); //Creates a new File instance 
			File file_2 = new File("E:\\年少有为copy.txt");//Creates a new File instance 
			file_2.createNewFile();
			FileInputStream a = new FileInputStream(file_1);//Creates a FileInputStream
			FileOutputStream b = new FileOutputStream(file_2);//Creates a file output stream to write to the file 
			byte[] date = new byte[1024];//Define an array
			int i = 0;
			while((i = a.read(date))>0) {
				b.write(date);
			}
			a.close();//Closes this file input stream and releases any system resources associated with the stream
			b.close();//Closes this file output stream and releases any system resources associated with the stream
			System.out.println("文件复制成功");
			
			FileReader fr = new FileReader("E:\\年少有为copy.txt");
			//Creates a new FileReader, given the File to read from.
			BufferedReader br = new BufferedReader(fr);//Reads text from a character-input stream
			String s = null;
			System.out.println("文件信息:");
			while ((s = br.readLine()) != null) { //Reads a line of text.
			System.out.println(s);
			}
		}
		
		catch(IOException exc) {
			exc.printStackTrace();
		}
		
	}
}

运行结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值