黑马程序员-----Java基础-----IO流-4

来源:互联网 发布:windows系统安装u盘 编辑:程序博客网 时间:2024/06/03 23:44

-----<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

IO流学习-4
import java.io.IOException;
import java.io.RandomAccessFile;
 RandomAccessFile 随机读写
 
 该类不是io体系中子类
 而是直接继承自Object。
 
 但是它是io包中成员,因为它具备读和写功能。
 内部封装了一个数组,而且通过指针对数组的元素进行操作。
 可以通过getFilePointer获取指针位置。
 同时通过 seek改变指针的位置  重点。
 
 其实完成读写的原理就是内部封装了字节输入流和输出流。
 
 通过构造函数可以看出,该类只能操作文件。
 而且操作文件还有模式: 只读--r  读写--rw
 
 如果模式为只读 r,不会创建文件,获取读取一个已存在文件,不存在,会报异常。
 而且该对象的构造函数要操作的文件不存在,会自动创建,如果存在不会覆盖。

import java.io.*;
public class test1 {
public static void main(String[] args)throws IOException 
{
//writeFile();

//readFile();
writeFile2();
}
public static void writeFile2()throws IOException
{
RandomAccessFile raf =new RandomAccessFile("ran.txt","rw");
raf.seek(8*3);
raf.write("手气".getBytes());
raf.writeInt(103);

raf.close();
}
public static void readFile()throws IOException
{
// TODO Auto-generated method stub
RandomAccessFile raf =new RandomAccessFile("ran.txt","r");

//调整对象中指针
//raf.seek(8);

//跳过指定的字节数
raf.skipBytes(8);

byte[] buf =new byte[4];
raf.read(buf);

String name = new String(buf);
int age =raf.readInt();

System.out.println("age="+age);
System.out.println("name="+name);

raf.close();
}
public static void writeFile() throws IOException
{
// TODO Auto-generated method stub
RandomAccessFile raf =new RandomAccessFile("ran.txt","rw");
raf.write("李四".getBytes());
raf.writeInt(98);
raf.write("李五".getBytes());
raf.writeInt(97);

raf.close();
}
}
--------------
package IO4;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.stream.FileImageInputStream;


//DataStream
 可以用于操作基本数据类型的数据流对象。
import java.io.*;
public class test2 {
public static void main(String[] args)throws IOException
{
//writeData();
readData();
}
public static void readData()throws IOException
{
// TODO Auto-generated method stub
DataInputStream dis = new DataInputStream(new FileInputStream("date.txt"));
int num = dis.readInt();
boolean b =dis.readBoolean();
double d = dis.readDouble();

System.out.println("num="+num);
System.out.println("b="+b);
System.out.println("d="+d);

dis.close();
}
public static void writeData()throws IOException
{
// TODO Auto-generated method stub
DataOutputStream dos = new DataOutputStream(new FileOutputStream("date.txt"));
dos.writeInt(234);
dos.writeBoolean(true);
dos.writeDouble(990.324);

dos.close();
}
}
--------------
package IO4;
 用于操作字节数组的流对象
 
 ByteArrayInputStream 在构造的时候,需要接受数据源,而且数据源是一个字节数组。
 
 ByteArrayOutputStream 在构造时,不要定义数据目的,因为该对象中已经内部封装了
 长度可变的字节数组,这就是目的地。
 
 因为这两个流对象操作的数组,并没有使用系统资源,不需要关闭。
 
 流操作规律
 源 
 键盘  system.in  硬盘FileStream    内存ArrayStream
 目的
 控制台   system.out  硬盘 FileStream       内存ArrayStream
 
import java.io.*;
public class test3 {

public static void main(String[] args) {

//数据源
ByteArrayInputStream bis =new ByteArrayInputStream("dfkwehfkw".getBytes());

//明确数据目的
ByteArrayOutputStream bos =new ByteArrayOutputStream();

int by =0;
while((by =bis.read())!= -1)
bos.write(by);

System.out.println(bos.size());
System.out.println(bos.toString());
}
}
------------
package IO4;

 编码表 Encode
 常见的:
 ASCII  美国标准信息交换码
 ISO8859-1 拉丁码表,欧洲
 GB2312 中国的中文编码表
 GBK 升级版   两个字节表示一个字符
 Unicode 国际标准码  文字都用两个字节表示java使用。
 UTF-8 最多 用三个字节表示一个字符
 
import java.io.*;
public class test4 {
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
//writeText();

readText();
}
public static void readText()throws IOException
{
// TODO Auto-generated method stub
InputStreamReader isr =new InputStreamReader(new FileInputStream("gbk.txt"),"UTF-8");
char[] buf = new char[10];
int len =isr.read(buf);
String str = new String(buf, 0 ,len);
System.out.println(str);
isr.close();
}
public static void writeText() throws IOException
{
// TODO Auto-generated method stub
OutputStreamWriter osw =
new OutputStreamWriter(new FileOutputStream("UTF.txt"),"UTF-8");
osw.write("你好");
osw.close();
}
}
------------
package IO4;

import java.lang.reflect.Array;
import java.util.Arrays;

 编码: 字符串变成 字节数组。
 
 解码: 字节数组变成字符串。
 
 String-->byte[]    str.getBytes();
   
 byte[]-->String new String(byte[] ,charsetName);
 

public class test5 {
public static void main(String[] args) throws Exception
{
String s = "你好";
byte[] b1 =s.getBytes("UTF-8");//编码
 
System.out.println(Arrays.toString(b1));

String s1= new String(b1,"GBK");//解码

System.out.println("s1="+s1);

//解码错误,重新编码,在解码.u8和gbk都识别中文,注意。
byte[] b2 =s1.getBytes("GBK");
System.out.println(Arrays.toString(b2));

String s2 =new String(b2,"UTF-8");
System.out.println("s2="+s2);
}
}
--------------
package IO4;

public class test6 {
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub
String s ="联通";
byte[] by =s.getBytes("GBK");
for(byte b: by)
System.out.println(Integer.toBinaryString(b&255));
}
}

 U8解码
 字节1   0
 
 字节1   110
 字节2   10
 
 字节1   1110
 字节2   10
 字节3   10
 
 第一个字节中文自动gbk解码
 不是u8解码

---------------
package IO4;

 有五个学生,每个学生有三门课的成绩
 从键盘输入以上数据(姓名。三门课成绩)
 输入格式如:zhangsan,30,40,60计算出总成绩
 
 并把学生的信息和计算出的总分数高低顺序存放在磁盘文件“stud.txt”中。
 
 分析:
 1.描述学生对象。
 2.定义一个可以操作学生对象的工具类。
 
 思路:
 1,通过获取键盘录入一行数据,并将该行数据信息取出,封装成学生对象。
 2,因为学生对象很多,那么就需要存储,使用集合,要对分数排序,
 可以使用Treeset。
 3,将集合中的信息写入到一个文件中。

import java.io.*;
import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int ma ,cn,en;
private int sum;
Student(String name,int ma,int cn ,int en)
{
this.name =name ;
this.ma =ma;
this.cn =cn;
this.en =en;
sum =ma+cn+en;
}
public int compareTo(Student s)
{
int num =new Integer(this.sum).compareTo(new Integer(s.sum));
if(num== 0)
return  this.name.compareTo(s.name);
return num;
}

public String getName()
{
return name;
}
public int getSum()
{
return sum;
}
public int hashCode()
{
return name.hashCode()+sum*39;
}
public boolean equals(Object obj) 
{
if(obj instanceof Student)
return false;
Student s =(Student)obj;

return this.name.equals(s.name)&&this.sum==s.sum;
}
public String toString()
{
return "Student["+name+","+ma+","+cn+","+en+"]";
}
}
class tool
{
//键盘输入,集合存储,如果排序不是想要的需要逆转,可以加入一个比较器
//comparator<Student> cmp
public static Set<Student> getStudents() throws IOException
{
return getStudents(null);
}
public static Set<Student> getStudents(Comparator<Student> cmp) throws IOException
{
BufferedReader bfr =
new BufferedReader(new InputStreamReader(System.in));
String line =null;

Set<Student> stus =null;
if(cmp==null)//判断是否需要用比较器
stus= new TreeSet<Student>();
else
stus = new TreeSet<Student>(cmp);

while((line =bfr.readLine())!= null)
{
if("over".equals(line))
break;
String [] info = line.split(",");

Student stu =new Student(info[0],Integer.parseInt(info[1]),
Integer.parseInt(info[2]),
Integer.parseInt(info[3]));

stus.add(stu);
}
bfr.close();
return stus;
}
//将上一步得到的返回值传到这一步中遍历用
public static void write(Set<Student> stus)throws IOException
{
BufferedWriter bfw =
new BufferedWriter(new FileWriter("infoo.txt"));
for(Student s :stus)
{
bfw.write(s.toString()+"\t");
bfw.write(s.getSum()+"");
bfw.newLine();
bfw.flush();

}
bfw.close();
}
}
public class test7 {

public static void main(String[] args)throws IOException 
{
//返回一个反向比较器
Comparator<Student> cmp =Collections.reverseOrder();
Set<Student> stus =tool.getStudents(cmp);
tool.write(stus);
}
}
------------
package IO4;

import java.io.PipedInputStream;
import java.io.PipedOutputStream;

import javax.management.RuntimeErrorException;

//管道流  理解 成对使用
//PipedInputStream
//PipedOutputStream
//
public class test8 {

public static void main(String[] args)throws Exception
{
// TODO Auto-generated method stub

PipedInputStream in =new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
in.connect(out);

read r = new read(in);
write w = new write(out);

new Thread(r).start();
new Thread(w).start();
}
}
class read implements Runnable
{
private PipedInputStream in;
read(PipedInputStream in)
{
this.in = in;
}

public void run()
{
try {
byte[] buf =new byte[1024];

int len = in.read(buf) ;
String s= new String(buf,0,len);
System.out.println(s);

in.close();

} catch (Exception e) {
throw new RuntimeException("yichang");
}
}
}
class write implements Runnable
{
private PipedOutputStream out;
write(PipedOutputStream out)
{
this.out=out;
}
public void run()
{
try {
out.write("piped laile".getBytes());

out.close();
} catch (Exception e) {
throw new RuntimeException("chucuole");
}
}
}


-----<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

0 0
原创粉丝点击