Java第十八天-IO流,其他流
//打印流
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PrintStream ps = new PrintStream(fos,true);//创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
if (ps != null) {
System.setOut(ps);}// 把标准输出流(控制台输出)改成文件,改变程序输出的位置
for (int i = 0; i <= 255; i++) { //输出ASCII字符
System.out.print((char)i);
if (i % 50 == 0) { //每50个数据一行
System.out.println(); // 换行
} }
ps.close();
输入输出流
/*
* 标准的输入输出流: 输入流:System.in 输出流: System.out
*/
// 从键盘输入,让小写的字母转换为大写的字母
BufferedReader br = null;
try {
InputStream is = System.in;
InputStreamReader isr = new InputStreamReader(is);// 将输入的字节转换为字符
br = new BufferedReader(isr);
String str;// 用str接受输入的字符串
while (true) {
System.out.println("请输入字符串");
str = br.readLine();
if (str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")) {
break;
}
String str1 = str.toUpperCase();//用str1接收转化后的str字符串
System.out.println(str1);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
转换流
用法与缓冲流一样
对象流
/*
- 要实现序列化的类:1.要求此类时可序列化的:实现Serializable接口
- 2.要求类的属性也要实现Serializable接口
- 3.提供一个版本号:pirvate static final long serialVersionID
- 4.使用static或transient修饰的属性不可序列化
*/
//对象的反序列化过程:将硬盘种的文件通过ObjectInputStream转换为相应的对象
@Test
public void testObjectIntputStream(){
ObjectInputStream ois = null;
try{
ois = new ObjectInputStream(new FileInputStream("person.txt"));
Person p1 = (Person)ois.readObject();
System.out.println(p1);
Person p2 = (Person)ois.readObject();
System.out.println(p2);
}catch (Exception e){
e.printStackTrace();
}finally{
if(ois!=null){
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// 对象的序列化过程:将内存中的对象通过ObjectOutputStream转换为二进制流,存储在硬盘中
@Test
public void testObjectOutputStream() {
Person p1 = new Person("天天", 23);
Person p2 = new Person("鸣人", 24);
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(
"person.txt"));
oos.writeObject(p1);
oos.flush();
oos.writeObject(p2);
oos.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(oos!= null){
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class Person implements Serializable {
private String name;
private Integer age;
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}