文件对象
File类
——在Java 中,File 类是 java.io 包中唯一代表磁盘文件本身的对象,也就是说,如果希望在程序中操作文件和目录,则都可以通过 File 类来完成。该类抽象的方式代表文件名和目录路径名。该类主要用于文件和目录的创建、文件的查找和文件的删除等操作。
File类常用获取文件的方法
方法 | 说明 |
---|---|
getName() | 返回由此抽象路径名表示的文件或目录的名称 |
getParent() | 返回此抽象路径名的父路径名的路径名字符串 |
getParentFile() | 返回此抽象路径名的父路径名的抽象路径名 |
getAbsoluteFile() | 返回此抽象路径名的绝对路径名形式 |
getAbsolutePath() | 返回此抽象路径名的绝对路径名字符串 |
length() | 返回此抽象路径名表示的文件长度 |
list()/list(FilenameFilter filter) | 返回文件和目录的名称所组成字符串数组(带过度) |
案例引入:
//1、给目录file1下添加文件world.txt //2、给目录file2下添加file22/file33目录; //3、判断file3目录里有无子集,没有则删除file3目录 //4、上述操作结束:求一下0913下有多少目录;有多少文件;分别输出这些目录和文件的名称
package Demo;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class Demo1 {
private int fileNum = 0;
private int dicNum = 0;
public static void main(String[] args) throws IOException {
File file = new File("E://0913");
//判断0913这个目录是否存在
if(!file.exists()){
//不存在 创建
}else {
//先删除,在创建
file.delete();
}
file.mkdir();
add();
//查看0913下的所有一级文件对象
System.out.println("查看所有文件:"+ Arrays.toString(file.list()));
Demo1 d = new Demo1();
d.printFile(file);
System.out.println("文件个数:"+d.fileNum);
System.out.println("目录个数:"+d.dicNum);
}
/*
增加新的文件夹
*/
public static void add() throws IOException {
File file1 = new File("E://0913//hello.txt");
file1.createNewFile();
File file2 = new File("E://0913//hello1.txt");
file2.createNewFile();
File f1 = new File("E://0913//file1");
f1.mkdirs();
f1=new File("E://0913//file1//world.txt");
try {
f1.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
File f2 = new File("E://0913//file2");
f2.mkdirs();
f2=new File("E://0913//file2//file22//file33");
f2.mkdirs();
File f3 = new File("E://0913//file3");
f3.mkdirs();
if (f3.length()==0){
//空文件删除
f3.delete();
}
}
public void printFile(File file){
if (file.isFile()){
System.out.println("文件名:");
fileNum++;
}else {
System.out.println("目录名:");
dicNum++;
}
System.out.println(file.getName());
if (file.isDirectory()){
File[] files = file.listFiles();
for (File f:files){
printFile(f);//递归调用
}
}
}
}
流的分类
字节流
InputStream (读文件) 实现类FileInputStream
OutputStream (写文件)实现类FileOutputStream
一次一字节
int i;
while((b = fis.read)!= -1){
// System.out.print((char)b);
fos.write(b);//写
}
一次一数组
byte[] buffer = new byte[1024];//每次读取一个字节数组 1k
int len;//每次读取的字节长度
while((len = fis.read(buffer))!= -1){
os.write(bytes,0,len);//写
// System.out.print(new String(buffer,0,len));
}
注意
FileInputStream fis = new FileInputStream("E://hello.txt");
FileOutputStream fos = new FileOutputStream(E://hello.txt);//会清空之前数据写入新的数据(覆盖)
FileOutputStream fos = new FileOutputStream(E://hello.txt,true);//不会清空之前数据(追加)
图片复制案例引入
package Demo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileInputStreamDemo {
public static void main(String[] args) {
FileInputStream fis = null;//文件字节输入流
FileOutputStream fos = null;//文件字节输出流
try {
fis = new FileInputStream("E://0913//113.png");
fos = new FileOutputStream("E://0913//file1//113.png",true);
//输入流
int i = 0;
try {
while ((i=fis.read())!=-1){
// System.out.print((char) i);//避免不了中文乱码
//输出
fos.write(i);
}
System.out.println("复制成功!");
//输出
// fos.write("Java".getBytes());
-----------------------------------------------
//定义字节数组转移数据(另一种方式)
byte [] bytes = new byte[1024];//1k
int len;
while ((len = is.read(bytes))!=-1){
os.write(bytes,0,len);
}
System.out.println("复制完成!");
-----------------------------------------------
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
try {
if(fis !=null){
fis.close();
}
if(fos !=null){
fos.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
字符流
Reader (读文件) 实现类 FileReader
Writer (写文件) 实现类 FileWriter
一次一字符
int code;
while(code=fr.read()!=-1){
//读 System.out.print((char)code);
}
//写
fw.write(98);
fw.write('a');
fw.write('许');
一次一字符数组
//读
char []buffer = new char[1024];
int len;
while((len = fr.read(buffer))!=-1){
String rs = new String(buffer,0,len);
System.out.print(rs);
}
//写
fw.write("abc我爱中国!");//字符数组
fw.write(chars,3,4);//字符数组的一部分
fw.write("abc我爱中国!",0,5);//字符串一部分
其他:
//StringBuffer装所有字符
int ch;
StringBuffer buffer=new StringBuffer();
while ((ch = reader.read()) != -1) {
buffer.append((char) ch);
}
fw.write(buffer.toString());
//
文档复制案例引入:
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("E://0913//唐诗.txt");
fw = new FileWriter("E://0913//copy.txt");
int i ;
while((i = fr.read())!=-1) {
fw.write(i);
System.out.println((char)i);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
fr.close();
fw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
案例引入:
将 静夜思*李白*窗前明月光*疑是地上霜*举头望明月*低头思故乡
写入copy.txt 中 格式如下:
实现:
package Demo;
import java.io.*;
import java.util.Arrays;
public class FileReaderWriterDemo {
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
BufferedReader br = null;
BufferedWriter br1 = null;
try {
fr = new FileReader("E://0913//唐诗.txt");
fw = new FileWriter("E://0913//copy.txt");
int i;
StringBuffer buffer=new StringBuffer();
while((i = fr.read())!=-1){
buffer.append((char) i);
}
String str = buffer.toString();
System.out.println(str);
//转成数组形式 用split()对数组进行分割
String [] arr = str.split("\\*"); //注意这里要用转义符号否则会报错(与系统的乘号冲突)
//转回字符串形式
System.out.println(Arrays.toString(arr));
//遍历输出
for (String a:arr) {
fw.write(a+";\n");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
fr.close();
fw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
字节流&字符流区分:
字节流 | 字符流 | |
---|---|---|
基本单元 | 单个字节 | 单个字符(Unicode码元(大小2字节)) |
是否具有缓冲区 | 不使用 | 使用缓冲区 |
处理数据类型 | 任意类型 | 文本数据 (world 文件不属于) |
父类*(基类) | InputStream/OutputStream | Reader/Writer |
音频、视频等 | 可以使用 | 不可以使用 |
缓冲流
——字节缓冲流(如BufferedInputStream与BufferedOutputStream)
——字符缓冲流(如BufferedReader与BufferedWriter)
使用带缓冲的字符流按行读取文本内容
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("hello1.txt"));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
}
对象流
——对象序列化
public void writeObj(){
ObjectOutputStream oos = null;
FileOutputStream fs = null;
try {
fs = new FileOutputStream("E://0913//hello1.txt");
oos = new ObjectOutputStream(fs);
oos.writeObject(new Book("《废话文学》","王孙","Aiit"));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (oos !=null){
oos.close();
}
if (fs !=null){
fs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
——对象反序列化
public void readObj(){
ObjectInputStream ois = null;
FileInputStream fis = null;
try {
fis = new FileInputStream("E://0913//hello1.txt");
ois =new ObjectInputStream(fis);
Book r = (Book) ois.readObject();
System.out.println(r);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(ois!=null) {
ois.close();
}
if(fis!=null) {
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}