文件的读取和写出
要读取一个文件,有以下几个步骤:
1.建立与文件的联系:File对象,文件必须存在
2.选择流:按字节流读取,文件输入流 InputStream FileInputStream
3.操作:byte[] car=new byte[1024]+read
4.释放资源,注意jdk1.7后会自动关闭了
InputStream是一个抽象类,不能new一个新的对象,所以这里使用多态
InputStream is=new FileInputStream(......);
选择构造方法,第一个和第三个比较常用,本质上来说这两种方法是一致的,通过String name 创建一个新对象,
它内部还是会通过name包装成File

在读取文件时,使用循环不断进行读取,定义一个制定长度的byte数组,则这个数组就是每次读取文件的长度,
如果要输出,就创建一个String对象,String info = new String(car, 开始, 结束);
样例:
package com.pony1223.byteio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Demo01 {
public static void main(String[] args)
{
// 1、建立联系 File对象
File src = new File("E:/study/java/HelloWorld.java");
// 2、选择流
InputStream is = null; // 提升作用域
try
{
is = new FileInputStream(src);
// 3、操作 不断读取 缓冲数组
byte[] car = new byte[1024];
int len = 0; // 接收 实际读取大小
// 循环读取
StringBuilder sb = new StringBuilder();
while (-1 != (len = is.read(car)))
{
// 输出 字节数组转成字符串
String info = new String(car, 0, len);
sb.append(info);
}
System.out.println(sb.toString());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
System.out.println("文件不存在");
} catch (IOException e)
{
e.printStackTrace();
System.out.println("读取文件失败");
}
finally
{
try
{
// 4、释放资源
if (null != is)
{
is.close();
}
}
catch (Exception e2)
{
System.out.println("关闭文件输入流失败");
}
}
}
}
文件写出,有以下几个步骤:
1.建立与文件的联系:File对象,文件可不存在
2.选择流:按字节流写出,文件输出流 OutputStream FileOutputStream
3.操作:write+flush
4.释放资源,注意jdk1.7后会自动关闭了
FileOutputStream的构造方法
FileOutputStream(File file,boolean append) 如果选择true,则是追加,false则覆盖
构造方法中没有append参数的,则默认false,覆盖

package com.pony1223.byteio;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Demo02
{
public static void main(String[] args)
{
File dest=new File("E:/study/java/test.txt");
OutputStream os=null;
try {
os=new FileOutputStream(dest);
String str="hahahaha";
//字符串转字节数组
byte[] data=str.getBytes();
os.write(data,0,data.length);
//强制刷新出去
os.flush();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
if(null!=os){
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

浙公网安备 33010602011771号