1.输入和输出
1:Output,将字节输出到磁盘。
2:Input,将字节出入到JVM。
2.OutputStream
1:字节输出流,每次只操作文件中的一个字节。
2:可以写任意文件。
3.OutputStream中的方法
1:void write(int b);
2:void write(byte[] b);
3:void write(byte,int start,int length);
4:void close();
4.FileOutputStream
1:文件不存在,可以根据路径创建一个文件,如果存在直接覆盖。
public static void main(String[] args)throws IOException {
FileOutputStream fos = new FileOutputStream("d:\\demo\\a.txt");//Windows下的分隔符是\,但是\是转移字符,所以写两个\\,表示第一个\将第二个\转为普通的\.
fos.write(100);//将100转为二进制写入记事本,记事本在打开时,查看二进制表,发现是100转为d。
fos.close();;
}
byte[] bytes = new byte[]{49,48,48};
fos.write(bytes);//写入100
fos.write("你好啊".getBytes());//字符串转为字节数组直接写入
2:文件的续写。
FileOutputStream(String pathname,boolean append);
FileOutputStream fos = new FileOutputStream("d:\\demo\\a.txt",true);
3:\r\n,换行
fos.write("\r\n".getBytes());
5.IO的异常处理
FileOutputStream fos = null ;
try {
fos = new FileOutputStream ( "d:\\demo\\a.txt" , true ) ;
} catch ( IOException e) {
System . out. println ( e. getMessage ( ) ) ;
throw new RuntimeException ( "文件创建失败" ) ;
} finally {
try {
if ( fos != null )
fos. close ( ) ;
} catch ( IOException e) {
System . out. println ( e. getMessage ( ) ) ;
throw new RuntimeException ( "资源关闭失败" ) ;
}
}
6.InputStream的方法
1:int read();读取下一个字节,读取到文件结尾时返回-1。
2:int read(byte[] bytes);读取一个字节,并存入byte[],返回值是读取字节的长度,结尾返回-1,数组可以进行缓冲,提高效率。
7.FileInputStream读取文件
FileInputStream fileInputStream = null ;
try {
fileInputStream = new FileInputStream ( "d:\\demo\\a.txt" ) ;
byte [ ] bytes = new byte [ 1024 ] ;
int len = 0 ;
while ( ( len = fileInputStream. read ( bytes) ) != - 1 ) {
String s = new String ( bytes, 0 , len) ;
System . out. println ( s) ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
if ( fileInputStream != null ) {
try {
fileInputStream. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
8.文件的复制
InputStream is = null ;
OutputStream os = null ;
try {
is = new FileInputStream ( "d:\\demo\\a.txt" ) ;
os = new FileOutputStream ( "d:\\demo\\a1.txt" ) ;
byte [ ] bytes = new byte [ 1024 ] ;
int len = 0 ;
while ( ( len = is. read ( bytes) ) != - 1 ) {
os. write ( bytes, 0 , len) ;
}
} catch ( IOException e) {
System . out. println ( e. getMessage ( ) ) ;
throw new RuntimeException ( "文件复制失败" ) ;
} finally {
if ( os != null ) {
try {
os. close ( ) ;
} catch ( IOException e) {
throw new RuntimeException ( "关闭os失败" ) ;
} finally {
if ( is != null ) {
try {
is. close ( ) ;
} catch ( IOException e) {
throw new RuntimeException ( "关闭is失败" ) ;
}
}
}
}
}