首页 > 代码库 > JavaLearning:IO

JavaLearning:IO

package org.fun.classdemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class OutputStreamDemo {

	public static void main(String[] args) throws IOException {
		File file = new File("d:" + File.separator + "demo.txt");
		OutputStream out = null;
		out = new FileOutputStream(file,true);
		String str = "hello wrold,JavaLearning!";
		byte b[] = str.getBytes();
		for (int i = 0; i < b.length; i++) {
			out.write(b[i]);
		}
		out.close();
	}
}

package org.fun.classdemo;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class WriterDemo {

	public static void main(String[] args) throws IOException {
		File file = new File("d:" + File.separator + "demo.txt");
		Writer out = null;
		out = new FileWriter(file);
		String str = "hello wrold";
		out.write(str);
		out.close();
	}
}

package org.fun.classdemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamDemo {

	public static void main(String[] args) throws IOException {
		File file = new File("d:" + File.separator + "demo.txt");
		InputStream input = null;
		input = new FileInputStream(file);
		byte[] b = new byte[(int) file.length()];// 开辟空间接收读取的内容
		for (int i = 0; i < b.length; i++) {
			b[i] = (byte) input.read();// 一个个的读取数据
		}
		System.out.println(new String(b));
		input.close();
	}
}

package org.fun.classdemo;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class ReaderDemo {

	public static void main(String[] args) throws IOException {
		File file = new File("d:" + File.separator + "demo.txt");
		Reader input = null;
		input = new FileReader(file);
		char[] b = new char[(int) file.length()];// 开辟空间接收读取的内容
		for (int i = 0; i < b.length; i++) {
			b[i] = (char) input.read();// 一个个的读取数据
		}
		System.out.println(new String(b));
		input.close();
	}
}

package org.fun.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Copy {

	public static void main(String[] args) throws Exception {
		if (args.length != 2) {
			System.out.println("操作语法错误");
			System.out.println("ex:java Copy file1 file2");
			System.exit(1);
		}
		if(args[0].equals(args[1])){
			System.out.println("无法复制自身文件");
			System.exit(1);
		}
		File file1=new File(args[0]);
		if(file1.exists()){
			File file2=new File(args[1]);
			InputStream input=new FileInputStream(file1);
			OutputStream output=new FileOutputStream(file2);
			int temp=0;
			while((temp=input.read())!=-1){
				output.write(temp);
			}
			System.out.println("copy success");
			input.close();
			output.close();
		}else{
			System.out.println("源文件不存在");
		}
		
	}
}