JAVA 文件操作(3)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mingzhuo_126/article/details/83549000

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();
		}
		
	}
}

运行结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mingzhuo_126/article/details/83549000
今日推荐