目标
运用File类进行文件操作
理解流,标准输入/输出流的概念
运用FileInputStream和FileOutputStream类读写文本文件
FileReader & FileWriter
BufferedReader & BufferedWriter
ObjectInputStream & ObjectOutputStream
Serializable
InputStreamReader
Properties
【文件可认为是相关记录或放在一起的数据的集合】
package test2;
/**
* 遍历F:\\java路径下的所有文件
*/
import java.io.File;
public class Demo {
public static void main(String[] args) {
File file=new File("F:\\java");
print(file);
}
public static void print(File file){
if(file.isDirectory()){
File files[]=file.listFiles();
for(File f:files){
print(f);
}
}else{
System.out.println(file.getName());
}
}
}
运行结果:
a.txt
b.zip
gg.bmp
java.txt
test.txt
session.rar
ss.bmp
test.php
c.bmp
a.txt
d.txt
33.php
p.zip
package test3;
import java.io.File;
public class A {
public static void main(String[] args) {
File file=new File("F:\\new\\a");
if(!file.exists()){
System.out.println(file.mkdir());//要创建文件夹a,但F盘下没有new文件夹,因此返回false
System.out.println(file.mkdirs());//要创建文件夹a,但F盘下没有new文件夹,mkdirs()创建了new和a
}
}
}
package test3;
import java.io.File;
import java.io.IOException;
public class A {
public static void main(String[] args){
File file=new File("F:\\java\\b.txt");
if(file.exists()){
System.out.println(file.length());//显示的是文件中的字节数
System.out.println("该文件大小:"+Math.ceil(file.length()/1024.0)+"KB");
}else{
try{
file.createNewFile();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
文件的读写
读
FileInputStream, FileReader
写
FileOutputStream,FileWriter
用FileInputStream 读文件
引入相关的类
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
构造一个文件输入流对象
InputStream fileobject = new FileInputStream("text.txt");
利用文件输入流类的方法读取文本文件的数据
fileobject.available(); //可读取的字节数
fileobject.read(); //读取文件的数据
关闭文件输入流对象
fileobject.close();
用FileOutputStream 写文本文件
利用文件输出流的方法写文本文件
String str ="好好学习Java";
byte[] words = str.getBytes();
fos.write(words, 0, words.length);//会将文本中原来里面的数据内容覆盖掉
关闭文件输出流
fos.close();
如:
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Demo {
public static void main(String[] args) {
FileInputStream fis=null;
try {
File file=new File("a.txt");
fis=new FileInputStream(file);
while(fis.available()>0){
System.out.print((char)fis.read());//一个汉字占两个字节,一旦a.txt里面出现汉字就会出错
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fis!=null){
try {
fis.close();//将输入流关闭
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
或者
package test;
/**
* copy file
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo2 {
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream("D:\\firefox.exe");
fos=new FileOutputStream("E:\\recv\\firefox.exe");//输出流中的firefox.exe即使没有也不可省略,FileOutputStream会自动创建它
byte[] data=new byte[30*1024];//大小要足够大
int length=fis.read(data);//read将从fis中读取的数据放到data中,data再返回一个int类型的长度
fos.write(data,0,length);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(fos!=null)
fos.close();
if(fis!=null)
fis.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class Demo {
public static void main(String[] args) throws Exception {
File file=new File("F://data//new.txt");
if(!file.exists()){
file.createNewFile();
}
OutputStream fos=new FileOutputStream(file);//将信息写到输出流中,然后到达对应的文件中
String str=new String("java and php");
byte[] files=str.getBytes();
fos.write(files, 0, files.length);
InputStream fis=new FileInputStream(file);//将文件中的信息读入到输入流中,通过输入流到达程序中
while(fis.available()>0){
System.out.println((char)fis.read());
}
}
}
FileReader
FileWriter
BufferedReader
BufferedWriter
package test;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Demo3 {
public static void main(String[] args) {
BufferedWriter buf=null;
Writer writer=null;
try {
writer = new FileWriter("123.txt");
buf=new BufferedWriter(writer);//最后关闭的时候先关buf,后关writer,因为buf中要用到writer
buf.write("adgfds");
buf.flush();
} catch (Exception e1) {
e1.printStackTrace();
}finally{
try {
if(buf!=null)
buf.close();
if(writer!=null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ObjectInputStream
ObjectOutputStream
**对象的序列化Serializable **
java.io.NotSerializableException
如果类没有实现Serializable接口,当使用ObjectOutputStream写类的实例时就会抛出上面的异常
java.io.Serializable
该接口内没有定义任何方法
类必须实现了这个接口才能被ObjectInputStream和ObjectOutputStream使用。
Eg:
public class Student implements Serializable {}
写对象:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(new Student());
读对象:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Object o = ois.readObject();
当需要对多个对象进行存取时,可以先将对象封装到List或Set对象中
Eg:
List<Student> students = new ArrayList<Student>();
students.add(new Student(“terry”));
students.add(new Student(“lucy”));
oos.writeObject(students);
读取时,使用:
List<Student> students = (List<Student>)ois.readObject();
package test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Student implements Serializable{
private String name;
int age;
static List<Student>students=new ArrayList<Student>();
static{
students.add(new Student("terry"));
students.add(new Student("lucy"));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student() {
}
public Student(String name) {
this.name=name;
}
@Override
public String toString() {
return "Student [name=" + name + "]";
}
}
package test;
/**
* 当需要对多个对象进行存取时,可以先将对象封装到List或Set对象中
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
public class Demo {
public static void main(String[] args) {
ObjectOutputStream oos=null;
ObjectInputStream ois=null;
try {
oos = new ObjectOutputStream(new FileOutputStream("b.txt"));
ois = new ObjectInputStream(new FileInputStream("b.txt"));
oos.writeObject(Student.students);
oos.flush();
List<Student>list=(List<Student>)ois.readObject();//readObject返回对象,集合也是对象
for(Student ss:list){
System.out.println(ss);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(oos!=null)
oos.close();
if(ois!=null)
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/*BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter("12.txt"));
bw.write("hello world!");
bw.newLine();
bw.write("hello world!");
bw.flush();
} catch (Exception e1) {
e1.printStackTrace();
}*/
}
}
运行结果:
Student [name=terry]
Student [name=lucy]
InputStreamReader
使用FileReader读取文件时,程序将假定文件使用系统默认的编码。对于中文操作系统,程序会以”gbk”编码来读取文件,如果文件的真实编码为”utf-8”,则读出来的字符将全是乱码。
可以使用InputStreamReader来读取这样的文件:
InputStreamReader isr =
new InputStreamReader(new FileInputStream(“file”), “utf-8”);
Properties
Properties具有和HashMap一样的方法,如get, put等。
提供了getProperty和setProperty方法,主要针对字符串进行操作。
提供load方法,用于从文件中加载key-value对
Properties文件一般使用.properties作为扩展名
加载完文件中的数据后,需要关闭流
可以通过setProperty添加数据,也可以通过“new–>File–>新建ss.properties文件”
Properties prop = new Properties();
prop.setProperty(“name”, “terry”);
prop.setProperty(“password”, “32few”);
prop.setProperty(“host”, “192.168.0.1”);
//…
String host = prop.getProperty(“host”);
String name = prop.getProperty(“name”);
可以使用如下方式将文件中的数据加载至Properties对象中:
Properties prop = new Properties();
FileInputStream fis = new FileInputStream(“F: \\p.properties”);
prop.load(fis);
String host = prop.getProperty(“host”);
String name = prop.getProperty(“name”);
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import java.util.Scanner;
public class Demo8 {
public static void main(String[] args) {
Properties p=new Properties();
Scanner in=new Scanner(System.in);
System.out.println("请输入你想加的键值:");
String key=in.nextLine();
System.out.println("请输入你想加的值:");
String value=in.nextLine();
p.setProperty(key, value);
FileOutputStream out=null;
try {
//FileOutputStream打开文件的方式默认是覆盖,就是一旦执行了上面这句,那么原有文件中的内容被清空,所以你在还没有加载p.store(out, "这是注释")的时候就把文件清空了
out = new FileOutputStream("new.properties",true);//加个true就可以了
p.store(out, "这是注释");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(out!=null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}