您的位置:首页 > 编程语言 > Java开发

Java io流一些工具练习 转换流,内存流

2017-04-01 17:48 204 查看
学习心得
一、专业课
1转换流
转化流

*将字节流转为字符流之间
*1.使用特定码表读写文件
*2.可以结合缓冲流
读的时候需要确保文件存在
1.1BufferedReader
privatestatic
void bReader()throws Exception{
/*
*
配合缓冲区转换流
*/
Filefile = new File(("D:"+File.separator+"d4.txt"));
FileInputStreamfis = new FileInputStream(file);
InputStreamReaderisr = new InputStreamReader(fis,"utf-8");
BufferedReaderbReader = new BufferedReader(isr);
char[]cbuf = new char[1024];
intlen = 0;
while(-1 != (len = bReader.read(cbuf))) {
System.out.println(newString(cbuf,0,len));
}
}

1.2OutputStreamWriter
privatestatic void
outputWriter()throws Exception{

/*
* OutputStreamWriter
将字符流转为字节流
*/
OutputStreamWriterosWriter = new OutputStreamWriter(new FileOutputStream(newFile("D:"+File.separator+"d4.txt")),"utf-8");
osWriter.write("星期九");
osWriter.flush();
osWriter.close();
}

1.3
20000
标准输入输出流
Scannerscanner = new Scanner(System.in);
//字节输入流
InputStreamis = System.in;
//字节打印流
PrintStreamps = System.out;
ps.println("dd");

InputStreamReaderisr = new InputStreamReader(is);
char[]cbuf = new char[1024];
intlen = isr.read(cbuf);
ps.println(len+" "+new String(cbuf,0,len));

1.4内存流
/*
内存流:

*
操作的是内存,以内存作为参考点。节点流
* ByteArrayInputStream
bais 读入内存
ByteArrayOutputStream
写出内存
内存流可以不关闭
*/
ByteArrayInputStreambais = new ByteArrayInputStream("星星".getBytes());
byte[]bytes = new byte[1024];
intlen = bais.read(bytes);

ByteArrayOutputStreambaos = new ByteArrayOutputStream();
baos.write(bytes,0, len);
System.out.println(newString(bytes,0,len));
System.out.println(baos.toString("utf-8"));
System.out.println(baos.toString());

1.5对象流与序列化
/**
*
对象流将对象的属性数据通过文件操作保存
ObjectInputStreamObjectOutputStream
*
用什么方式将对象的信息(数据)持久性的保存?最好保存到
文件当中
*
为什么呢?对象由Java的类创建,当Java程序执行完,该对象
会被jvm回收
*
序列化:将对象的属性值写入文件
*
反序列化:将文件里面的对象属性的数据转为对象调用的形式
*
静态属性与方法不会被序列化
* transient
修饰的属性不会被序列化
*/
1.5.1写对象
FileOutputStreamfos
= new FileOutputStream(new File("d:" + File.separator+
"d6.txt"));
ObjectOutputStreamoos = new ObjectOutputStream(fos);
oos.writeObject(student);
oos.flush();
oos.close();
fos.close();
1.5.2读对象
FileInputStreamfis = new FileInputStream(new File("d:" + File.separator+ "d6.txt"));
ObjectInputStreamois = new ObjectInputStream(fis);
Studentstudent2 = (Student) ois.readObject();
System.out.println(student2);
ois.close();
fis.close();
1.5.3序列化注意
虚拟机是否允许反序列化,不仅取决于类路径和功能代码是否一致,一个非常重要的一点是两个类的序列化ID是否一致(就是privatestatic
final long serialVersionUID = 1L)。如果两个类的功能代码完全一致,但是序列化ID不同,他们无法相互序列化和反序列化
序列化ID在Eclipse下提供了两种生成策略,一个是固定的1L,一个是随机生成一个不重复的long类型数据(实际上是使用JDK工具生成),在这里有一个建议,如果没有特殊需求,就是用默认的1L就可以,这样可以确保代码一致时反序列化成功。那么随机生成的序列化ID有什么作用呢,有些时候,通过改变序列化ID可以用来限制某些用户的使用
2.小组PK
2.1我方题目

1.阅读以下代码,若能运行输出运行结果,若不能运行说明原因:
publicclass Note {
publicstatic void main(String[] args) {
newB(5);
}
}
abstractclass A {
abstractvoid method();
A(){
System.out.println("A()before method()");
method();
System.out.println("A()after method()");
}
}
classB extends A {
intradius = 1;
B(intr) {

radius= r;
System.out.println("radius= " + radius);
}
voidmethod() {
System.out.println("radius= " + radius);
}
}
A()before method()
radius= 1//正确答案是radius
=0
A()after method()
radius= 5
解析:两个考点,1.父类中定义的抽象方法,子类中重写后父类可以直
接调用该方法。
2.类在实例化对象时,先给变量和方法分配空间,不进行其他操作,

后调用父类的无参
构造方法,即super(),调用完之后才给该对象的成员变量进行赋值。

2.写出下列程序输出结果。
publicstatic void main(String[] args) {
inti = 0;
Integera = 126;
Integerb = 126;
ArrayList<Integer>list = new ArrayList<>();

for(intj = 0;j < 6;j++){
list.add(j);
}
try{
for(i= 0;i < list.size()/2;i++){
list.add(i+3,0);
intnum = 4 / list.get(list.size() - i - 1);
list.remove(list.size()- i - 1);

}
}catch (Exception e) {
System.out.println(a== b);
System.out.println(list);
}finally{
a+=i;
b+=i;
System.out.println(a== b);
System.out.println(i);
}
}
}
答案:
true
[0,1, 2, 0, 0, 0, 4]
false
2

3.请找出程序中的受检异常,以及会使程序产生运行时异常的错误代码。
publicclass Test {
publicstatic void main(String[] args) {
ArrayList<Object>list = new ArrayList<>();
list.add(null);
Vector<Object>vector = new Vector<>();
vector.add(null);
HashSet<Object>hashSet = new HashSet<>();
hashSet.add(null);
hashSet.add(null);
TreeSet<Object>treeSet = new TreeSet<>();
treeSet.add(null);
HashMap<Object,Object>hashMap = new HashMap<>();
hashMap.put(null,null);
hashMap.put(null,1);
hashMap.put(1,null);
HashTable<Object,Object>hashTable = new HashTable<>();
hashTable.put(null,null);
hashTable.put(1,null);
hashTable.put(null,1);
TreeMap<Object,Object>treeMap = new TreeMap<>();
treeMap.put(null,null);
treeMap.put(1,null);
treeMap.put(null,1);

}
}
答案:
受检异常:
HashTable<Object,Object>hashTable = new HashTable<>();HashTable拼写错误,正确为:Hashtable
运行时异常:
treeSet.add(null);
TreeSet不能存储空
hashTable.put(null,null);
hashTable.put(1,null);
hashTable.put(null,1);
HashTable键和值都不可以为空
treeMap.put(null,null);
treeMap.put(null,1);
TreeMap
键不能为空

4.publicclass Test01 {
publicstatic void main(String[] args) throws IOException {

fun1();
InputStreamReaderisr = new InputStreamReader(System.in,"gbk");
BufferedReaderbReader = new BufferedReader(isr);
char[]cbuf = new char[1024];
intlen = 0;
len= bReader.read(cbuf);
System.out.println(len+ " " + new String(cbuf,0,len));

}
privatestatic void fun1() throws IOException {
InputStreamis = System.in;
PrintStreamps = System.out;
InputStreamReaderisr = new InputStreamReader(is);
char[]cbuf = new char[1024];
intlen = 0;
do{
len= isr.read(cbuf);
ps.println(len+" "+new String(cbuf,0,len));
}while (len<2);
ps.println(len+" "+new String(cbuf,0,len));
}

}
请注意程序输出格式
程序从控制台输入1回车后程序输出什么?
3 1 //当输入1回车时缓冲区中的字符是这个:
1\r\n
3 1
程序从控制台输入12回车后程序输出什么?
412

5.填空
publicclass Test1 {
//程序功能,从一个txt中读取算式,计算并输出到指定txt中,注意输
出的格式,注意格式,注意格式
//String.charAt()返回指定位置的字符
//String.indexOf()返回指定字符在字符串中的位置
//subString()
字符串截取
publicstatic void main(String[]
args) throws IOException {
FileReaderreader = new FileReader(new
File("E:\\exam.txt"));
BufferedReaderbr = new BufferedReader(reader);
FileWriterwriter = new FileWriter(new
File("E:\\test.txt"));
BufferedWriterbw = new BufferedWriter(writer);
Stringstring = "";
while((string= br.readLine())!=null){
intresult = 0;
intfhPos = 0;
if(string.indexOf("+")> -1){
fhPos= string.indexOf("+");

}else{
fhPos= string.indexOf("-");
}
Stringnum1 = string.substring(_0,fhPos__________);
//取第一个数
Stringnum2 = string.substring(_fhPos__+
1______); //取第二个数
int n1 = Integer.parseInt(num1);
int n2 = Integer.parseInt(num2);

bw.write(_string_);
_bw.flush()_________________; //这里是bw
bw.write(__"="____);
__bw.flush()_______________; //这也是bw
if(string.indexOf("+")> -1){
result=n1+n2;

}else{
result=n1-n2;

}
__bw.write(String.valueOf(result));_________;
//这也是bw
bw.newLine();
}
br.close();
bw.close();

}
}

exam.txt:

12+32
23-434
34+34
99+1
22+43
23-23
23+232
test.txt:
12+32=44
23-434=-411
34+34=68
99+1=100
22+43=65
23-23=0
23+232=255

2.2对手题目
1.阅读以下程序,如果报错,指出报错位置和原因,如果能运行,写出
运行结果
bytebyte1 = 1;
bytebyte2 = 2;
bytebyte3 = byte1 + byte2; //强转byte

ArrayListlist = new ArrayList<>();
list.add(byte3);
list.add("hi");
list.addAll(list);

System.out.println(list.size());

for(Object object : list) {
System.out.print(object+"");
}

Stringstring1 = "you";
StringBufferstring2 = new StringBuffer("!");

String[]strings = new String[4];

strings[0]= "how";
strings[1]= new String("are");
strings[2]= string1;

strings[3]= string2; //StringBuffer需
要转换成String
System.out.println(strings.length()); //strings是数组,length属性,没哟()
for(int j = 0; j < strings.length; j++) {
System.out.print(strings[j]+"");
}

Stringstring3 ="hi";
System.out.println(string3.length); //string3是
字符串,使用length方法

2.看程序写结果,有错改错后写出结果,没错请直接写出结果:
publicclass Lianxi06 {
publicstatic void main(String[] args) {

for(inti=1;i<=10;i++){
intnum=Math.sqrt(i); //double
转换int需要强

for(intj=2;j<=num;j++){
if(i%j==0){
break;
}
if(j==num){
System.out.println(i);
break;
}
}
}
}
}
5
7

3.有错改错并输出结果,没错请输出结果:
packagecom.demo;
publicclass Demo03 {
publicstatic void main(String[] args) {
Outer.Innerinner = new Outer.Inner(); //
inner.fun();
}
}
classOuter {
staticint a = 10;
staticfinal int c = 50;
publicvoid method() {

System.out.println("外部method方法");
}
classInner {
intb = 20;
inta = 20;
publicvoid fun() {
System.out.println(this.a);
System.out.println(Outer.this.a);
System.out.println(a);
}
}
}

答案:
Outer.Innerinner = new Outer().new Inner();
20
10
20

4.输出结果:

(程序中,abc.txt文件的长度为6字节)
publicstatic void main(String[] args) {
Filef1 = new File("D:\\abc.txt");
Filef2 = new File("D:\\abc.txt");

Integeri1 = (int) f1.length();
Integeri2 = (int) f2.length();
Strings1 = f1.getAbsolutePath();
Strings2 = f1.getPath();
Strings3 = new String(f2.getAbsolutePath());
Strings4 = new String(f2.getPath());

System.out.println(s1== s2);

System.out.println(s3.equals(s1));

System.out.println(s3== s4);

System.out.println(s3.equals(s4));

System.out.println(i1== i2);

System.out.println("6".equals(f1.length()));

}
true
true
false
true
true
false

5.以下程序是否有编译错误,如果有,注释掉编译错误后,阅读程序并
写出运行结果
publicclass Demo08 {
publicstatic void main(String[] args) {
System.out.println(fun1());

}
privatestatic int fun1() {
try{

inta = 1;
intb = 0;
try{
intc= a/b;
thrownew Exception();
System.out.println("异常");
//这句之前抛出异
常,所以无法执行到,会有编译错误
}catch (ArithmeticException e) {
returna+b;
}
finally{
a++;b++;
}
}catch (Exception e) {
e.printStackTrace();
}
return0;
}
}
注释掉编译错误后,运行结果为
1

学习心得:
1.发现对面的对手时,也不可大意,真正的对手可能在背后偷笑
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 转换流 内存流