//循环等待输出键盘输入数据 package io; import java.io.IOException; public class TestSystemInRead { public static void main(String[] args) { int c; try { while((c = System.in.read())!=0) { System.out.write(c); } } catch (IOException e) { e.printStackTrace(); } } }
//输出字节数组数据 package io; import java.io.IOException; public class TestSystemInRead { public static void main(String[] args) { try { byte[] b = new byte[100]; System.in.read(b); System.out.write(b,0,100); } catch (IOException e) { e.printStackTrace(); } } }
//循环等待输出键盘输入数据 package io; import java.io.IOException; public class TestSystemInRead { public static void main(String[] args) { try { while(true){ byte[] b = new byte[100]; System.in.read(b);//键盘输入到字符数组b,控制台输入回车后一次读取,按字节 String str = new String(b); System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } } }
package io; import java.io.FileNotFoundException; import java.io.IOException; //RandomAccessFile随机访问文件类,可随意读写文件 import java.io.RandomAccessFile; public class TestRandomAccessFile { public static void main(String[] args) { try { RandomAccessFile rafile = new RandomAccessFile("f:/testrw.txt" ,"rw"); // byte[] bw = new byte[3]; // bw[0] = 100;//d // bw[1] = 101;//e // bw[2] = 102;//f // rafile.write(bw); //rafile.writeBoolean(true); rafile.writeBytes("AAAA"); //rafile.writeChars("DDDD"); rafile.writeUTF("中国"); //read也有相关的函数 rafile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } } }
//管道流通常用在多线程的系统中,一个线程可以随机往输出流管道写入数据, //另一个线程可以随时从输入管道读取数据,达到异步传输数据 package io; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; public class TestPipedInputStream { public static void main(String[] args) { try { PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); //从输出流写入数据 byte[] b = new byte[3]; b[0] = 100; b[1] = 101; b[2] = 102; pos.write(b); //从输入流读取数据 while(pis.available()>0) { int c = pis.read(); System.out.print((char)(c)); } pis.close(); pos.close(); } catch (IOException e) { e.printStackTrace(); } } }
package io; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; //不建议对这两个管道流对象使用单个线程,可能造成死锁 public class TestPipedOutputStream { public static void main(String[] args) { Sender sender = new Sender(); PipedOutputStream out = sender.getOutputStream(); Receiver receiver = new Receiver(); PipedInputStream in = receiver.getInputStream(); try { out.connect(in); } catch (IOException e) { e.printStackTrace(); } new Thread(sender).start(); new Thread(receiver).start(); } } //发送者线程类 class Sender extends Thread { private PipedOutputStream out = new PipedOutputStream(); public PipedOutputStream getOutputStream() { return out; } public void run() { String s = new String ("My heart will go on, i love u!"); try { out.write(s.getBytes()); out.close(); } catch (IOException e) { e.printStackTrace(); } } } //接收者线程类 class Receiver extends Thread{ private PipedInputStream in = new PipedInputStream(); public PipedInputStream getInputStream() { return in; } public void run() { String s = null; byte[] buf = new byte[1024]; try { int len = in.read(buf); s = new String(buf,0,len); System.out.println("receive:"+ s); } catch (IOException e) { e.printStackTrace(); } } }
package io; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.LineNumberInputStream; //LineNumberInputStream可以跟踪行号,设置行号,对行做标记以便恢复 public class TestLineNumberStream { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("f:\\test1.txt"); LineNumberInputStream lis = new LineNumberInputStream(fis); DataInputStream dis = new DataInputStream(lis); String line; while((line = dis.readLine())!=null) { System.out.println(lis.getLineNumber()+": " +line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package io; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PushbackInputStream; //推回重读的能力 public class TestPushbackInputStream { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("f:\\test1.txt"); PushbackInputStream pis = new PushbackInputStream(fis); int c = pis.read(); System.out.println((char)c); pis.unread(c);//推回一个字节 c= pis.read(); System.out.println((char)c); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package io; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; //Windows中使用ISO8859-1,也称为ANSI代码 //该代码页面使用UTF-8 public class TestCharsetChanged { public static void main(String[] args) { Charset cset = Charset.forName("UTF-8"); //对Unicode字符串进行编码 String str = "多年后,我终于发现,我依然爱着你,SS"; ByteBuffer buffer = cset.encode(str); byte[] bytes = buffer.array(); //对一个字节序列解码,需要一个字节缓冲区。 //使用ByteBuffer的静态方法wrap方法把一个字节数组转化为一个字节缓冲区。 ByteBuffer bbuf = ByteBuffer.wrap(bytes); CharBuffer cbuf = cset.decode(bbuf); String str1 = cbuf.toString(); System.out.println(str1); } }
package io; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.StringTokenizer; public class DataFileTest { public static void main(String[] args) { Employee[] staff = new Employee[3]; staff[0] = new Employee("Elena",7600,1987,02,13); staff[1] = new Employee("Cathrine",8700,1983,02,13); staff[2] = new Employee("Stephon",9800,1981,03,23); try { //save all employee records to the file employee.dat PrintWriter out = new PrintWriter(new FileWriter("f:\\employee.dat")); writeData(staff,out); out.close(); // BufferedReader in = new BufferedReader(new FileReader("f:\\employee.dat")); Employee[] newstaff = readData(in); for(Employee e: newstaff) { System.out.println(e.toString()); } } catch (IOException e) { e.printStackTrace(); } } static void writeData(Employee[] employees, PrintWriter out) throws IOException { out.println(employees.length);//write number of the array employees for(Employee e :employees) { e.writeData(out); } } static Employee[] readData(BufferedReader in) throws IOException { int n = Integer.parseInt(in.readLine()); Employee[] employees = new Employee[n]; for(int i=0;i<n;i++) { employees[i] = new Employee(); employees[i].readData(in); } return employees; } } class Employee { private String name ; private double salary; private Date hireDay; public Employee(){} public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month-1, day); hireDay = calendar.getTime(); } public void writeData(PrintWriter out) throws IOException { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(hireDay); out.println(name+ "|" + salary + "|" + calendar.get(Calendar.YEAR)+"|" +(calendar.get(Calendar.MONTH)+1)+"|" + calendar.get(Calendar.DAY_OF_MONTH) ); } public void readData(BufferedReader in) throws IOException{ String s = in.readLine(); StringTokenizer t = new StringTokenizer(s,"|"); name = t.nextToken(); salary = Double.parseDouble(t.nextToken()); int y = Integer.parseInt(t.nextToken()); int m = Integer.parseInt(t.nextToken()); int d = Integer.parseInt(t.nextToken()); GregorianCalendar calendar = new GregorianCalendar(); calendar.set(y, m-1, d); hireDay = calendar.getTime(); } public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDay() { return hireDay; } public void raiseSalary(double byPercent) { double raise = salary * byPercent /100; salary += raise; } public String toString() { return this.getClass().getName()+"[name="+name + ",salary="+salary + ",hireDay="+hireDay +"]"; } }NIO
package io; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.zip.CRC32; //计算文件的32位循环冗余校验和(CRC32) public class NIOTest { public static long checksumInputStream(String filename) throws IOException { InputStream in = new FileInputStream(filename); CRC32 crc = new CRC32(); int c; while((c= in.read()) != -1) { crc.update(c); } return crc.getValue(); } public static long checksumBufferedInputStream(String filename) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(filename)); CRC32 crc = new CRC32(); int c; while((c= in.read()) != -1) { crc.update(c); } return crc.getValue(); } public static long checksumRandomAccessFile(String filename) throws IOException { RandomAccessFile file = new RandomAccessFile(filename,"r"); long length = file.length(); CRC32 crc = new CRC32(); for(long p=0; p<length; p++) { file.seek(p); int c = file.readByte(); crc.update(c); } return crc.getValue(); } //通过NIO映射文件的方式访问文件 public static long checksumMappedFile(String filename) throws IOException { FileInputStream in = new FileInputStream(filename); //FileChannel通道时对于磁盘文件的抽象,允许访问操作系统的特性,如文件的内存映射、文件锁定、快速传输数据 FileChannel channel = in.getChannel(); CRC32 crc = new CRC32(); int length = (int) channel.size(); //得到映射 MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length); for(int p=0; p<length; p++) { int c = buffer.get(p); crc.update(c); } return crc.getValue(); } public static void main(String[] args) throws IOException { System.out.println("InputStream"); long start = System.currentTimeMillis(); long crcValue = checksumInputStream("f:\\quanxian.xml"); long end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end-start)+ "milliseconds");//1250milliseconds System.out.println("BufferedInputStream"); start = System.currentTimeMillis(); crcValue = checksumBufferedInputStream("f:\\quanxian.xml"); end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end-start)+ "milliseconds");//47milliseconds System.out.println("RandomAccessFile"); start = System.currentTimeMillis(); crcValue = checksumRandomAccessFile("f:\\quanxian.xml"); end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end-start)+ "milliseconds");//1860milliseconds System.out.println("MappedFile"); start = System.currentTimeMillis(); crcValue = checksumMappedFile("f:\\quanxian.xml"); end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end-start)+ "milliseconds");//109milliseconds } }