输入和输出流
InputStream抽象了应用程序读取数据的方式,即输入流(读)。
OutputStream抽象了应用程序写出数据的方式,即输出流(写)。
FileInputStream和FileOutputStream类的使用
1.使用read()方法读取文件
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream("D:\\java\\z.txt");
//读一个字节
int len=0;
while((len=fis.read())!=-1){
System.out.println((char)len);
}
fis.close();
}
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream("D:\\java\\z.txt");
byte[] bytes=new byte [2];
int len=0;
while ((len=fis.read(bytes))!=-1) {
System.out.print(new String(bytes,0,len));
}
fis.close();
}
2 使用write()方法写入文件
public static void main(String[] args) throws IOException {
//明确地址
FileOutputStream fos= new FileOutputStream("D:\\java\\z.txt",true);
//写
//fos.write(100);
byte[] bytes={-66,-67,-68,-69};
fos.write("\r\n".getBytes());
fos.write("你好".getBytes());
//释放资源
fos.close();
}
3异常处理
public static void main(String[] args) {
FileOutputStream fos=null;
try {
fos = new FileOutputStream("D:\\java\\z.txt",true);
byte[] bytes={-66,-67,-68,-69};
fos.write("\r\n".getBytes());
fos.write("你好".getBytes());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
浙公网安备 33010602011771号