IO流实例

//字节流:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.junit.Test;

public class IOStreamTest {

//fileInputStreamTest
@Test
public void fileInputStreamTest(){

File file = new File("aa.txt");
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
FileOutputStream fos = new FileOutputStream("aa.txt");
String b1 = "aa222";
byte[] b = b1.getBytes();
fos.write(b);
FileInputStream fis = new FileInputStream("aa.txt");
byte[] by = new byte[(int)file.length()];//file.length()=5
int t;
int count =0;
//fis.read(by);//按照文件长度读取字节
//System.out.println(new String(by));//aa222
while((t=fis.read()) != -1 ){//读到文件末尾返回-1
by[count++] = (byte)t;
}
System.out.println(new String(by));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

posted @ 2017-03-06 16:33  ding9587  阅读(190)  评论(0编辑  收藏  举报