1 今天继续看书
DataOutputStream写文件
1 package File; 2 import java.io.IOException; 3 import java.io.FileOutputStream; 4 import java.io.DataOutputStream; 5 import java.io.OutputStream; 6 7 public class DataOutputStreamDemo { 8 public static void main(String[] args)throws IOException{ 9 write(); 10 } 11 public static void write()throws IOException{ 12 OutputStream os=new FileOutputStream("D:/Hello.txt"); 13 DataOutputStream dos=new DataOutputStream(os); 14 dos.writeInt(123); 15 dos.writeBoolean(true); 16 dos.writeByte(34); 17 dos.writeBytes("Hello"); 18 dos.writeChar(58); 19 dos.writeChars("java"); 20 dos.writeDouble(20.0); 21 dos.writeFloat(20f); 22 dos.writeShort(31); 23 dos.writeUTF("C++"); 24 dos.writeLong(13L); 25 dos.flush(); 26 dos.close(); 27 } 28 29 }
DataInputStream读数据
1 package File; 2 import java.io.DataInputStream; 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 7 public class DataInputStreamDemo { 8 public static void main(String[] args)throws IOException{ 9 read(); 10 } 11 public static void read()throws IOException{ 12 InputStream in =new FileInputStream("D:/Hello.txt"); 13 DataInputStream dis =new DataInputStream(in); 14 int a=dis.readInt(); 15 System.out.println(a); 16 System.out.println(dis.readBoolean()); 17 System.out.println(dis.readByte()); 18 System.out.println(dis.readChar()); 19 System.out.println(dis.readDouble()); 20 System.out.println(dis.readFloat()); 21 System.out.println(dis.readFloat()); 22 System.out.println(dis.readShort()); 23 System.out.println(dis.readLong()); 24 dis.close(); 25 26 } 27 28 }
内存操作流
1 package File; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.OutputStream; 5 import java.io.ByteArrayInputStream; 6 import java.io.ByteArrayOutputStream; 7 8 public class ByteOutputStreamDemo { 9 public static void main(String[] args)throws IOException{ 10 outin(); 11 } 12 public static void outin()throws IOException{ 13 String info ="hello Java"; 14 InputStream input=new ByteArrayInputStream(info.getBytes()); 15 OutputStream output=new ByteArrayOutputStream(); 16 int temp=0; 17 while((temp=input.read())!=-1){ 18 output.write(Character.toUpperCase((char)temp)); 19 } 20 String str =output.toString(); 21 input.close(); 22 output.close(); 23 System.out.println(str); 24 } 25 26 }
2 当用DataOutputStream写文件时,写出的文件会出现乱码
3 明天继续看书