目的
掌握Java语言中相关文件操作:用代码实现创建文件,将对象写入文件,将一个文件里面的东西通过代码转入到另一个里面,Java里面的输入输出流
相关技术、及其使用
创建一个文件:
创建一个文件首先要具备完整路径,然后在判断文件在所属路径下面是否已经存在。
String path = "/Andriod/day85/java5/src/main/java/day9";
//path/1.txt
File file = new File(path.concat("/1.txt"));
//判断是否存在
if(file.exists() == false) {
//不存在就去创建
file.createNewFile();
try { 抛出异常 如何处理
file.createNewFile();
}catch (IOException e){
System.out.println("IO异常了");
输入输出流:
输出流:从内存空间将数据写到外部设备(磁盘、硬盘、光盘)
输出流OutputStream 字节流 Writer字符流默认文件指针只向开头从文件开头写 write是接着文件里面的内容后免写
输入流:将外部数据写到内存中
流 stream 统一管理数据的写入和读取 开发者将内存里面的数据写到stream流里面 或者从流里面读取数据 输入输出流
向文件写入数据:
//向文件写入数据 字节流
//1、创建文件输出流对象
FileOutputStream fos = new FileOutputStream(file);
//调用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();
注意:当文件操作完毕后,要自己关闭文件。
读取文件里面的内容:
//读取内容 read
FileInputStream fis = new FileInputStream(file);
byte [] name1 = new byte[12];
fis.read(name1);
fis.close();
System.out.println(new String(name1));
FileReader fr = new FileReader(file);
char [] book = new char[4];
int count = fr.read(book);
fr.close();
System.out.println(new String(book));
向文件里面写入和读取一个对象:
Person xw = new Person();
xw.age = 20;
xw.name = "小王";
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);
ois.close();
写入对象时会碰到序列化:
保存的对象必须实现 serializable接口
如果对象内部还有属性变量是其他类的对象 那么这个类也必须实现serializable接口
将一个文件copy到另一个位置:
long start = System.currentTimeMillis();
//将一个文件copy到另外一个位置
//1、源文件的路径
String sourcePath = "C:/Users/asus/Desktop/1.jpg";
//2、目标文件的路径
String desPath = "/Andriod/day85/java5/src/main/java/day9/1.jpg";
//3、图片 视频 音频 字节
FileInputStream fis = new FileInputStream(sourcePath);//读出
FileOutputStream fos = new FileOutputStream(desPath);//写入
byte[] in = new byte[1024];
int count = 0;
while ((count = fis.read(in)) !=-1){
fos.write(in,0,count);
}
fis.close();
fos.close();
long end = System.currentTimeMillis();
System.out.println(end - start);
}
PS
文件的操作都是一些比较简单的操作,但是,在操作文件的时候一定要注意一点就是要保证所操作文件的路径存在并正确。运行出错往往就是文件的路径方面出现问题。
网友评论