文件字节流的输入和输出是根据程序而言的,从程序输出到文件中的称输出流:FileOutputStream;从文件输入到程序中的称输入流:FileInputStream。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileInOutDemo {
// 文件字节输入定义缓冲区时用小写byte
public static void main(String[] args) {
// TODO Auto-generated method stub
// 文件输出流
try {
FileOutputStream fos = new FileOutputStream("D:/test.txt");
String date = "到点了兄弟";
try {
fos.write(date.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 文件输入流
FileInputStream fis = null;
try {
fis = new FileInputStream("D:/test.txt");
byte[] bt = new byte[1024];
int lon = 0;
StringBuffer sb = new StringBuffer();
try {
while ((lon = fis.read(bt)) > 0) {
sb.append(new String(bt, 0, lon));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sb);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* FileInputStream fis = null; try { //得到一个输入流 fis = new
* FileInputStream("D:/test.txt"); //定义缓存区 1kb byte buf[] = new byte[1024];
* //实际读取到的字节数 int leng = 0;
*
* StringBuffer sb = new StringBuffer();
*
* while((leng = fis.read(buf)) > 0) { sb.append(new String(buf,0,leng)); }
*
* System.out.println(sb); } catch (FileNotFoundException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } catch (IOException e) { //
* TODO Auto-generated catch block e.printStackTrace(); } finally { try {
* fis.close(); } catch (IOException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } }
*/
}
}