IO流
1.字符流的写入和读出
@Test
public void test11(){
try {
FileWriter fw = new FileWriter(new File("aa.txt"));
fw.write("中国人真争气");
if (fw!=null)
{
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
FileReader fr = new FileReader(new File("aa.txt"));
char[] chars = new char[1024];
int let;
while ((let=fr.read(chars))!=-1)
{
String s = new String(chars, 0, let);
System.out.print(s);
}
if (fr!=null)
{
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
2.字节流的读取和写入
@Test
public void test13()
{
try {
FileInputStream fis = new FileInputStream(new File("trump.gif"));
FileOutputStream fos = new FileOutputStream(new File("taa.gif"));
byte[] bytes = new byte[1024];
int len;
while ((len=fis.read(bytes))!=-1)
{
fos.write(bytes,0,len);
}
if(fis!=null&&fos!=null)
{
fis.close();
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
3.流的转换
public class IOStreamTest4 {
@Test
public void test1()
{
FileInputStream fi = null;
InputStreamReader ir = null;
try {
fi = new FileInputStream("hello2.txt");
ir = new InputStreamReader(fi, "GBK");
char[] chars = new char[5];
int len;
while ((len=ir.read(chars))!=-1)
{
String s = new String(chars, 0, len);
System.out.print(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fi.close();
ir.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.使用对象流进行序列化
package IOStream;
import org.junit.Test;
import java.io.*;
public class IOStreamTest6 {
@Test
public void test1()
{
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("objec.txt"));
oos.writeObject(new String("我爱美国天安门"));
oos.flush();
oos.writeObject(new Person("王五",12));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos!=null)
{
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void test2()
{
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("objec.txt"));
Object obj = ois.readObject();
String str = (String) obj;
Person p = (Person) ois.readObject();
System.out.println(str);
System.out.println(p);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package IOStream;
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
public static final long serialVersionUID = 42778390854939L;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person() {
}
}