java用write()拷贝一个文本文件

总结:灵活运用循环语句,或条件判断语句。每一种流的正确使用方法;

这里是两种方法;

package com.ds;

import java.io.*;

public class tyut {

	/*public void copyFile(FileInputStream in, FileOutputStream out)
			throws IOException {
		int length;
		byte[] b = new byte[23533];
		try {
			while ((length = in.read()) != -1) {

				out.write(b, 0, 23453);
			}
		} catch (IOException E) {
			System.out.println("Error:" + E);
			System.out.println(-4);
		}

	}
*/
	public void copyFileByte(FileInputStream in, FileOutputStream out) {
		int i = 0;
		try {

			do {
				i = in.read();
				if (i != -1)
					out.write(i);

			} while (i != -1);

		} catch (IOException E) {
			E.printStackTrace();
		}// 只要是输入流输出流都会抛出非运行时异常IoXception

	}

	public static void main(String[] args) {
		FileCopy demo = new FileCopy();
		FileInputStream in;
		FileOutputStream out;
		try {
			in = new FileInputStream("dfa.ydy");
			out = new FileOutputStream("dsfa.tx");
			demo.copyFile(in, out);

		} catch (IOException e) {

			System.out.println("error:" + e);
			System.out.println(-4);
		}
	}

}

  

原文地址:https://www.cnblogs.com/langlove/p/3425205.html