在千锋逆战学习Java的第31天
加油!
今天学习了I/O框架
作业题
3.对于FileInputStream来说,从方向上来分,它是_____流,从数据单位上分,它是_____流,从功能上分,它是_____流。
答:输入,字节,节点
答:I. int ,从此输入流中读取下一个数据字节
II. 读入缓冲区的字节总数,如果因为已经到达流末尾而没有更s多的数据,则返回 -1
bs - 存储读取数据的缓s冲区
III.读入缓冲区的字节总数,如果因为已经到达流末尾而没有更多的数据,则返回 -1
bs - 存储读取数据的缓冲区
off - 目标数组 b 中的起始偏移量
len - 读取的最大字节数
答:AB
I.创建一个文件;向文件中写入值
II.追加写入值,不覆盖 ;会
7.代码改错
import java.io.FileInputStream;
public class TestFileInputStream {
public static void main(String[] args) {
FileInputStream fin = new FileInputStream("text.txt");
try{
System.out.println(fin.read());
fin.close();
}catch(Exception e){
}
}
}
main要声明异常,throws FileNotFoundException
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestHelloWorld {
public static void main(String[] args) {
FileOutputStream fos = null;
FileInputStream fis = null;
try {
fos = new FileOutputStream("test.txt",true);
String s = "Hello World";
fos.write(s.getBytes());
fis = new FileInputStream("test.txt");
byte[] b = new byte[11];
while (true) {
int count = fis.read(b);
if(count == -1) {
break;
}
if (fis.read(b) == -1) {
break;
}
for(int i = 0;i<count;i++) {
System.out.print((char)b[i]);
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果
13.(对象序列化)
为了让某对象能够被序列化,要求其实现 ____接口;
为了让该对象某个属性不参与序列化,应当使用 _____修饰符。
答:Serializable
transient
答:print(Object obj)是打印一个对象obj。
writeObject(Object obj) 将对象obj写入ObjectOutputstream中
16.有以下代码
import java.io.*;
public class TestSerializable {
public static void main(String[] args) throws Exception {
Address addr = new Address("Beijing", "100000");
Worker w = new Worker("Tom", 18, addr);
OutputStream os = new FileOutputStream("fout.dat");
ObjectOutputStream oout = new ObjectOutputStream(os);
oout.writeObject(w);
oout.close();
}
}
class Address {
private String addressName;
private String zipCode;
// 构造方法…
// get/set 方法…
public Address(String addressName, String zipCode) {
super();
this.addressName = addressName;
this.zipCode = zipCode;
}
}
class Worker implements Serializable {
private String name;
private int age;
private Address address;
// 构造方法…
// get/set 方法…
public Worker(String name, int age, Address address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
}
答:B
Exception in thread “main” java.io.NotSerializableException: