java I/O加强

import java.io.IOException;
import java.io.RandomAccessFile;

import org.junit.Test;
/*用RandomAccessFile,
 * 数据流可以理解成静态摊在地上,
 * 由我们根据游标(第一次开时从0开始)在指定位置更更改内容(以byte为单位),
 * 如果位置计算不准确,那么会把旧数据破坏了。
 * 读的时候也要精确计算出从什么位置开始读,读什么类型的数据(多长),
 * 否则数据读出来也是错误的。
 * 
 * raf创建一次,进行操作时,它的游标是连续变化的
 * 
 */
public class RandomAccessFileDemo {
    @Test
    public void w(){
    	try {
			RandomAccessFile raf=new RandomAccessFile("w.dxt", "rw");
			raf.writeInt(100);
			raf.write(97);
			raf.write(353);  //跟io流一样,write(int b)是只写最后一个字节数据:97
			
			raf.writeUTF("湖南城市学院");
			
			raf.close();
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
    }
    
    @Test
    public void r(){
    	
    	  try {
			RandomAccessFile raf=new RandomAccessFile("w.dxt", "r");
			int r=raf.readInt();
			System.out.println(r);
			
			raf.skipBytes(2); //控制游标往前跳2个字节
			String str = raf.readUTF();
			System.out.println(str);
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
    	  
    }
    
    @Test//要注意控制游标
	public void demo(){
		try {
			RandomAccessFile raf = new RandomAccessFile("b.txt", "rw");
			for(int i=0;i<4;i++){
				raf.writeDouble(3.14*i);
			}
			//此时游标在第4个浮点数的末尾
			
			//把游标定位到文件开始处
			raf.seek(16);//raf.seek(12);
			raf.writeDouble(0);
			
			raf.seek(0);
			for(int i=0;i<4;i++){
				double d = raf.readDouble();
				System.out.println(i+": "+d);
			}
			
			raf.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


import java.io.Serializable;

public class person implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String id; 
	private String name;
	private int age;
	private static int num;
	//transient private int age2;
	
	
	public person(String id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
		//this.age2 = age2;
		num++;
	}
	public person() {
		this(",","",0);
	}
	/**
	 * @return the id
	 */
	public String getId() {
		return id;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	
	public String toString() {
		return  id + ", " + name + ", " + age +num;
	}
	/**
	 * @return the num
	 */
	public static int getNum() {
		return num;
	}
	
	
}


import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.junit.Test;

/*
 * 被序列化的对象必须要实现Serializable接口
 * 序列化时,非静态变量都会存入对象图,静态变量和函数都是不会存入对象图的。
 * 如果某个非静态变量不想存入对象图,则可以把它声明成瞬时变量(transient)
 */
public class SerializableDemo {
	@Test
	public void t1() throws IOException {
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
				"p.dxt"));
		person p = new person("A001", "Jack", 20);
		person p2 = new person("A002", "张三", 22);

		System.out.println(p.getNum());
		System.out.println(p2.getNum());

		out.writeObject(p);
		out.writeObject(p2);

		out.close();
	}

	@Test
	public void t2() throws IOException {
		ObjectInputStream oin = new ObjectInputStream(new FileInputStream(
				"p.dxt"));
		while (true) {

			try {
				person p= (person) oin.readObject();
				System.out.println(p);
			} catch (EOFException e) {
				System.out.println("date ok!");
				break;
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		oin.close();
	}
}


import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import org.junit.Test;

public class bufferChoose {
   @Test 
   public void t1() throws IOException{
	   long t1=System.currentTimeMillis();
	   DataInputStream din=new DataInputStream
			   (new BufferedInputStream
					   (new FileInputStream("test.txt")));
	   
	   String str="";
	   while((str=din.readLine())!=null){
		   System.out.println(str);
	   }
	   
	   long t2 = System.currentTimeMillis();
		System.out.println("1:"+ (t2-t1) );
   }
   
	
	@Test
	public void t2() throws IOException{
		long t1 = System.currentTimeMillis();
		
		DataInputStream in = new DataInputStream(
						new FileInputStream("test.txt"));
		String str="";
		while( (str=in.readLine())!=null){
			System.out.println(str);;
		}
		
		long t2 = System.currentTimeMillis();
		System.out.println("2:"+ (t2-t1) );
	}
	
	@Test
	public void t3() throws IOException{
		long t1 = System.currentTimeMillis();
		
		BufferedInputStream in = new BufferedInputStream(
				                new DataInputStream(
				                		new FileInputStream("test.txt")));
		byte buf[] = new byte[30];
		while( in.available()>0 ){
			int len = in.read(buf);
			String str=new String(buf,0,len);
			System.out.println(str);;
		}
		
		long t2 = System.currentTimeMillis();
		System.out.println("3:"+ (t2-t1) );
	}
}





import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class transferStreamDemo {
	/*
	 * 需求:模拟英文聊天程序,要求: (1) 从键盘录入英文字符,每录一行就把它转成大写输出到控制台; (2) 保存聊天记录到字节流文件。
	 */

	/*
	 * 分步写 InputStream in = System.in; Reader r = new InputStreamReader(in);
	 * BufferedReader br = new BufferedReader(r);
	 */
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream("char.txt")));

		String str ="";
		while ((str = br.readLine()) != null) {
			System.out.println(str.toUpperCase());
			bw.write(str);
			bw.newLine();
		}

		br.close();
		bw.close();
	}
	
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.junit.Test;

//转换流功能2:字符编码转换
public class transferStreamDemo2 {
	// ///////////////读/////////////////////////

	@Test
	// 用默认编码(MyEclipse平台设置的编码)---依赖平台的编码
	public void readTextDecoding() throws IOException {
		// FileReader fr = new FileReader("files\\utf8.txt");
		FileReader fr = new FileReader("files\\gbk.txt");

		char cbuf[] = new char[128];
		int len = 0;
		while ((len = fr.read(cbuf)) != -1) {
			String str = new String(cbuf, 0, len);
			System.out.println(str);
		}
		fr.close();
	}

	// //※※※采用转换流以指定编码方式读※※※※////
	@Test
	// 用转换流指定编码去读---与平台的编码无关 : FileInputStream+指定编码+InputStreamReader
	public void readTextDecoding2() throws IOException {
		FileInputStream fin = new FileInputStream("files\\utf8.txt");
		InputStreamReader isr = new InputStreamReader(fin, "utf-8");

		// 用转换流指定字符编码
		// FileInputStream fin = new FileInputStream("files\\gbk.txt");
		// InputStreamReader isr = new InputStreamReader(fin, "gbk");

		char cbuf[] = new char[128];
		int len = 0;
		while ((len = isr.read(cbuf)) != -1) {
			String str = new String(cbuf, 0, len);
			System.out.println(str);
		}
		isr.close();
	}

	/*
	 * 用String的构造方法解决IO流的中文乱码: FileInputStream + new String(bs,"gbk")
	 * 缺陷:截取字节数据时,不要把一个完整的汉字拆开,否则会乱码
	 */
	@Test
	public void readTextDecoding3() throws IOException {
		FileInputStream fin = new FileInputStream("files\\gbk.txt");
		byte bs[] = new byte[128];
		int len = 0;
		;
		while ((len = fin.read(bs)) != -1) {
			String str = new String(bs, 0, len, "gbk");
			System.out.println(str);
		}
		fin.close();
	}

	// ///////////////写/////////////////////////
	@Test
	// FileWriter: FileOutputStream+默认编码表
	public void writeTextEncoding() throws IOException {
		FileWriter fw = new FileWriter("files\\utf-8_2.txt");
		fw.write("每天进步一点点.....");
		fw.close();
	}

	@Test
	// OutputStreamWriter + FileOutputStream + 默认编码表
	public void writeTextEncoding2() throws IOException {
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
				"files\\utf-8_2.txt"));
		osw.write("每天进步一点点.....222好的好的...");
		osw.close();
	}

	// //※※※采用转换流以指定编码方式写※※※※////
	@Test
	// OutputStreamWriter + FileOutputStream +指定编码表
	public void writeTextEncoding3() throws IOException {
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
				"files\\gbk2.txt"), "gbk");
		osw.write("每天进步一点点.....2333好的好的...");
		osw.close();
	}

}


猜你喜欢

转载自blog.csdn.net/lx678111/article/details/80183211