在IO流中,文件的读写算是最基本的操作了,这样就可以在一定程度上丰富了功能,文件的读写主要有下面几个步奏:
1:定义文件对象
2:定义输入或者输出流
3:循环遍历以字节的方式输入或者输出
package IO;
import java.io.*;
public class writeoupt {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File f7=new File("f:\\ff\\write.txt");
System.out.print("该文件已经存在");
// 开始写入
// 字节输出流
FileOutputStream fis1=null;
try {
fis1=new FileOutputStream(f7);
String str1="您好";
byte []bytes=new byte[1024];
fis1.write(str1.getBytes());
} catch (Exception e) {
// TODO: handle exception
}finally{
try {
fis1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 写入借宿,如果没有文件会自动创建
FileInputStream fis2=null;
try {
fis2=new FileInputStream(f7);
int count=0;
byte []bytes1=new byte[1024];
System.out.println("已经天津爱的内容如下:");
while((count=fis2.read(bytes1))!=-1){
String s=new String(bytes1,0,count);
System.out.print(s);
}
} catch (Exception e) {
// TODO: handle exception
}finally{
try {
fis2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}