File文件操作:
image.png
image.png
image.png
image.png
创建文件
String path ="D:/Java learning/java/src/main/java/day8";
File file = new File(path.concat("/1.txt"));
//判断是否存在
if(file.exists()==false){
// 不存在就创建
try{
file.createNewFile();
}catch (IOException e){
System.out.println("IO异常了");
}
}
向文件写入数据-字节流
// 1.创建文件输出流对象
FileOutputStream fos = new FileOutputStream(file);
// 2.调用write方法写入
byte[] text = {'1','2','3','4'};
fos.write(text);
// 3.操作完毕需要关闭stream对象
fos.close();
向文件写入数据-字符流
FileWriter fw = new FileWriter(file);
char[] name = {'安','卓','开','发'};
fw.write(name);
fw.close();
```
##读取内容(两种方式)
FileInputStream fis = new FileInputStream(file);
byte[] name = new byte[12];
int count = fis.read(name);
fis.close();
System.out.println(count+" "+new String(name));
FileReader fr = new FileReader(file);
char[] book = new char[4];
count = fr.read(book);
fr.close();
System.out.println(count+" "+new String(book));
image.png向文件里面存一个对象
序列化 serializable
保存的对象必须实现Serializable接口
如果对象内部还有属性变量是其他类的对象
这个类也必须实现Seriablizable接口
Dog wc = new Dog();
wc.name = "旺财";
Person xw = new Person();
xw.name = "小王";
xw.age = 20;
xw.dog = wc;
OutputStream os = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(xw);
oos.close();
//从文件里面读取一个对象
InputStream is = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(is);
Person xw = (Person) ois.readObject();
System.out.println(xw.name+" "+xw.age+" "+xw.dog.name);
ois.close();
使用BufferedInputStream 和 BufferedOutStream 提高读写的速度
image.png
RandomAccessFile 随机访问文件 使用seek定位访问的位置
image.png
自练小Demo
输入一串字符,以#号键结尾,将字符写入文件并显示到屏幕
public class Documents {
public static final String PATH = "D:/Java learning/java/src/main/java/day8/1.txt";
String password;
public static final String PATH2 = "D:/Java learning/java/src/main/java/day8/5.txt";
public static void main (String []args) throws IOException, ClassNotFoundException {
char ch;
int data;
FileInputStream fin = new FileInputStream(FileDescriptor.in);
FileOutputStream fout = new FileOutputStream(PATH);
System.out.println("请输入一串字符串,以#号结尾");
while((ch=(char)fin.read())!='#')
fout.write(ch); //写出一个字节数据
fin.close();
fout.close();
System.out.println();
fin = new FileInputStream(PATH);
fout = new FileOutputStream(FileDescriptor.out);
while(fin.available()>0){
fout.write(fin.read());
}
}
}
感悟:
多敲就完事了。
网友评论