h4 { margin-top: 0.49cm; margin-bottom: 0.51cm; line-height: 156%; page-break-inside: avoid; }h4.western { font-family: "Arial",sans-serif; font-size: 14pt; }h4.cjk { font-family: "黑体","SimHei"; font-size: 14pt; }h4.ctl { font-family: "DejaVu Sans"; font-size: 14pt; }p { margin-bottom: 0.21cm; }
FlileInputStream 和 FileOutputStream 分别用来创建磁盘文件的输入流和输出流对象,通过他们的构造函数来指定文件路径和文件名
创建FileInputStream 类时 指定的文件应该是存在可读的
创建FileOutputStream 实例对象时如果文件已存在 那么文件将会被覆盖
对同一个磁盘文件创建FileInputStream 的来两种方式
-
FileInputStream fileInputStream = new FileInputStream( " 文件名 " );
-
File file = new File( " 文件名 " );
FileInputStream fileInputStream = new FileInputStream( file );
用第二种方式在写入之前可以判断文件是否存在 之类的
创建 FileOutputStrem 实例对象的时候,可以指定还不存在的文件 但不能指定已被其他程序打开的程序文件
FileOutputStream 写入文件的方法
FileOutputStream fileOutputStream = new FileOutputStream( "src/cn/itcast/ioc/hello.txt" );
fileOutputStream.write( "wangxiang" .getBytes());
FileInputStream 读取文件的方法
File file = new File( "src/cn/itcast/ioc/hello.txt" );
FileInputStream fileInputStream = new FileInputStream(file);
byte [] buf = new byte [1024];
int len = 0;
len = fileInputStream.read(buf);
System. out .println( new String( new String(buf,0,len)));
注意 如果打印文件的时候 把全部的字节数组转换为字符串会出现乱码 ,所以用 string 另外一个构造方法 转换固定的长度