J2SE IO编程

文件目录:

源文件:

CopyFile.java    b0.jpg

运行程序后文件:

CopyFile.java    b0.jpg    Hongten.jpg

 

CopyFile.java

代码:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Hongten
 * 
 * @time 2011-9-3 2011
 */
public class CopyFile {
	public static void main(String[] args) {
		try {
		FileInputStream fis = new FileInputStream("b0.jpg");
		FileOutputStream fos = new FileOutputStream("Hongten.jpg");
		// 从此输入流中读取一个数据字节
		int read = fis.read();
		// 文件读取到末尾的时候,在读取就会变为-1,这时就标记着文件读取完
		while (read != -1) {
			fos.write(read);
			System.out.println(read);
			read = fis.read();
		}
		// 关闭输入流和输出流
		fis.close();
		fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

 

 

 

测试二:

源文件:

Test.java   b0.jpg

运行程序后文件:

Test.java   b0.jpg  Hongten.jpg

 

Test.java

代码:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Hongten
 * 
 * @time 2011-9-3 2011
 */
public class Test {
	public static void main(String[] args) {
		try{
		FileInputStream fis=new FileInputStream("b0.jpg");
		FileOutputStream fos=new FileOutputStream("Hongten.jpg");
		//用一个byte数组来保存我们将要读取的文件大小
		byte[] b=new byte[1024];
		//每次从文件中读取的大小,有b的大小决定
		int read=fis.read(b);
		while(read!=-1){
			fos.write(b,0,read);
			read=fis.read(b);
		}
		fis.close();
		fos.close();
	}catch(IOException e){
		e.printStackTrace();
	}
	}
}

 

 

测试三:

源文件:

CopyFile.java    hongten.java  

运行程序后文件:

CopyFile.java    hongten.java   hello.java

 

CopyFile.java

代码:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Hongten
 * 
 * @time 2011-9-3 2011
 */
public class CopyFile {
	public static void main(String[] args) {
	try {
		FileInputStream fis = new FileInputStream("hongten.java");
		FileOutputStream fos = new FileOutputStream("hello.java");
		// 从此输入流中读取一个数据字节
		int read = fis.read();
		// 文件读取到末尾的时候,在读取就会变为-1,这时就标记着文件读取完
		while (read != -1) {
			fos.write(read);
			read = fis.read();
		}
		// 关闭输入流和输出流
		fis.close();
		fos.close();
	} catch (IOException e) {
		e.printStackTrace();
	}

	}
}

 

测试四:

 

 

posted @ 2011-09-03 11:27  Hongten  阅读(469)  评论(0编辑  收藏  举报
Fork me on GitHub