public static final String separator。根据操作系统,动态的提供分隔符。
实例化方法
package com.atguigu.java;
import org.junit.Test;
import java.io.File;
/**
* @author ycy
* @create 2020 - 07 -13 -11:24 上午
*/
public class FileTest {
@Test
public void test(){
File file1 = new File("hello.txt");//相对于当前module
File file2 = new File("/Applications/studydea/JavaSenior");
System.out.println(file1);//hello.txt
System.out.println(file2);///Applications/studydea/JavaSenior
//构造器2
File file3 = new File("/Applications/studydea", "/JavaSenior");
System.out.println(file3);///Applications/studydea/JavaSenior
//构造器3
File file4 = new File(file3,"hi.txt");
System.out.println(file4);///Applications/studydea/JavaSenior/hi.txt
}
}
常用方法
File类的获取功能
public String getAbsolutePath():获取绝对路径
public String getPath() :获取路径
public String getName() :获取名称
public String getParent():获取上层文件目录路径。若无,返回null
public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
public long lastModified() :获取最后一次的修改时间,毫秒值
public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
未创建文件
@Test
public void test1(){
File file = new File("hello.txt");
File file1 = new File("/Applications/studydea/hi.txt");
// public String getAbsolutePath():获取绝对路径
String path = file.getAbsolutePath();
System.out.println(path);///Applications/studydea/JavaSenior/day8/hello.txt
//public String getName() :获取名称
System.out.println(file.getName());//hello.txt
// public String getPath() :获取路径
System.out.println(file.getPath());//hello.txt
//public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
System.out.println(file.length());//0
//public String getParent():获取上层文件目录路径。若无,返回null
System.out.println(file.getParent());//null
//public long lastModified() :获取最后一次的修改时间,毫秒值
System.out.println(file.lastModified());//0
String path1 = file1.getAbsolutePath();
System.out.println(path1);///Applications/studydea/hi.txt
//public String getName() :获取名称
System.out.println(file1.getName());//hi.txt
// public String getPath() :获取路径
System.out.println(file1.getPath());///Applications/studydea/hi.txt
//public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
System.out.println(file1.length());//0
//public String getParent():获取上层文件目录路径。若无,返回null
System.out.println(file1.getParent());///Applications/studydea
//public long lastModified() :获取最后一次的修改时间,毫秒值
System.out.println(file1.lastModified());//0
}
创建hello.txt后
@Test
public void test1(){
File file = new File("hello.txt");
File file1 = new File("/Applications/studydea/hi.txt");
// public String getAbsolutePath():获取绝对路径
String path = file.getAbsolutePath();
System.out.println(path);///Applications/studydea/JavaSenior/day8/hello.txt
//public String getName() :获取名称
System.out.println(file.getName());//hello.txt
// public String getPath() :获取路径
System.out.println(file.getPath());//hello.txt
//public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
System.out.println(file.length());//11
//public String getParent():获取上层文件目录路径。若无,返回null
System.out.println(file.getParent());//null
//public long lastModified() :获取最后一次的修改时间,毫秒值
System.out.println(new Date(file.lastModified()));//Mon Jul 13 12:09:26 CST 2020
String path1 = file1.getAbsolutePath();
System.out.println(path1);///Applications/studydea/hi.txt
//public String getName() :获取名称
System.out.println(file1.getName());//hi.txt
// public String getPath() :获取路径
System.out.println(file1.getPath());///Applications/studydea/hi.txt
//public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
System.out.println(file1.length());//0
//public String getParent():获取上层文件目录路径。若无,返回null
System.out.println(file1.getParent());///Applications/studydea
//public long lastModified() :获取最后一次的修改时间,毫秒值
System.out.println(file1.lastModified());//0
}
}
File类的重命名功能
public boolean renameTo(File dest):把文件重命名为指定的文件路径,要一个有一个没有
File类的判断功能
public boolean isDirectory():判断是否是文件目录
public boolean isFile() :判断是否是文件
public boolean exists() :判断是否存在
public boolean canRead() :判断是否可读
public boolean canWrite() :判断是否可写
public boolean isHidden() :判断是否隐藏
File类的创建功能
public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建
File类的删除功能
public boolean delete():删除文件或者文件夹
删除注意事项:
Java中的删除不走回收站。 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
IO流
从文件中读取数据
public class TestReaderWriter {
@Test
public void testFileReader() {
//1.实例化File对象,指明要操作的文件
File file = new File("hello.txt");
//2.提供具体的流
FileReader fr = null;
try {
fr = new FileReader(file);
//3.读入数据
//read():返回读入的字符,若达到文件末尾,则返回-1
int data = fr.read();
while (data!=-1){
System.out.print((char)data);
data = fr.read();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流的关闭方法
try {
if(fr!=null)
fr.close();//helloworld
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//read()操作升级,使用read的重载方法
@Test
public void testFileReader1(){
//1.实例化File
File file = new File("hello.txt");
FileReader fr = null;
try {
//2。流的实例化
fr = new FileReader(file);
//3。读入
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf))!=-1){//返回读入数组的字符个数,到末尾返回-1
// for (int i = 0; i < len; i++) { //不能用length,可能没有覆盖前一次读的数据
// System.out.print((cbuf[i]));
String str = new String(cbuf, 0, len);
System.out.print(str); //helloworld
}
// }
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源的关闭
if (fr!=null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
为了保证关闭操作一定能执行,需要采用try-catch-finally结构
读入文件一定要存在,否则会报FileNotFoundException
writer
@Test
public void testWriter() throws IOException {
File file = new File("hello1.txt");
FileWriter writer = new FileWriter(file);
writer.write("I have a dream");
writer.close();
}
说明:file可以不存在,如果不存在,在输出的过程中,会自动创建此文件。
若存在,若使用构造器:FileWriter(file, false)/FileWriter(file):对原有文件进行覆盖,使用FileWriter(file, true)则不会覆盖,在原有文件上追加内容
图片的复制与非文本文件(mp3,mp4,avi,doc等)不能通过字符流进行而需通过字节流处理,文本文件(txt,.c,.java,.cpp)需使用字符流读取
缓冲流
提供流的读取、写入速度
缓冲流为处理流,需要先建节点流FileReader等,再利用其进行实例化,在关闭资源时,要先关闭外层,后关闭内层,关闭外层流时会自动关闭内层流,
提速原因:定义了一个缓冲区
flush():清空缓冲区
转换流
标准输入流
package com.atguigu.java1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author ycy
* @create 2020 - 07 -14 -11:05 上午
*/
public class Test21 {
/*
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。
然后继续进行输入操作,直至当输入“e”或者“exit”时,退出程序。
*/
public static void main(String[] args) {
//方法一:
// Scanner scan =new Scanner(System.in);
// String str = null;
// while(!(((str = scan.next()).equals("e"))||(str.equals("exit")))){
// String upperCase = str.toUpperCase();
// System.out.println(upperCase);
// }
// scan.close();
// }
//方法二:使用System.in实现。System.in-->转换流--->BufferedReader的readLine()
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(isr);
String data;
try {
while (!(((data = bufferedReader.readLine()).equals("e"))||data.equals("exit"))){
String s = data.toUpperCase();
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader!=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
打印流
打印流:PrintStream和PrintWriter
提供了一系列重载的print()和println()方法,用于多种数据类型的输出
PrintStream和PrintWriter的输出不会抛出IOException异常
PrintStream和PrintWriter有自动flush功能
PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。
在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
System.out返回的是PrintStream的实例
PrintStream ps = null; try {
FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt")); // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区) ps = new PrintStream(fos, true);
if (ps != null) {// 把标准输出流(控制台输出)改成文件
System.setOut(ps); }
for (int i = 0; i <= 255; i++) { // 输出ASCII字符 System.out.print((char) i);
if (i % 50 == 0) { // 每50个数据一行
System.out.println(); // 换行 }
}
} catch (FileNotFoundException e) {
e.printStackTrace(); } finally {
if (ps != null) { ps.close();
}
}
数据流
对象流
用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
序列化:用ObjectOutputStream 类保存基本类型数据或对象的机制
反序列化:用ObjectInputStream 类读取基本类型数据或对象的机制
注意:对象所属的类必须是可以序列化的,ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从 而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。//当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
package com.atguigu.java;
import org.junit.Test;
import java.io.*;
/**
* @author ycy
* @create 2020 - 07 -14 -3:30 下午
*/
public class ObjectInputOutputStreamTest {
/*
序列化过程:将内存的java对象保存到磁盘中或通过网络传输出去
使用ObjectOutputStream
*/
@Test
public void test(){
ObjectOutputStream oos = null;
try {
//1.
oos = new ObjectOutputStream(new FileOutputStream(new File("object.dat")));
//2.
oos.writeObject(new String("啦啦"));
oos.flush();//刷新操作
} catch (IOException e) {
e.printStackTrace();
} finally {
//3.
try {
if (oos!=null)
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
反序列化过程
*/
@Test
public void test2(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object object = ois.readObject();
System.out.println(object);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois !=null)
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
自定义类想要序列化需要满足要求:
1.实现接口 Serializable
2.当前类提供一个全局常量:serialVersionUID
说明:private static final long serialVersionUID;
serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。
如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID可能发生变化,无法反序列化。故建议, 显式声明。
3.除了当前类要序列化以外,还要保证其内部所有属性是需要序列化的。(默认情况下,基本数据类型可以序列化)
4.ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量,transient修饰不可以被序列化的属性
package com.atguigu.java;
import java.io.Serializable;
/**
* @author ycy
* @create 2020 - 07 -14 -6:11 下午
*/
public class Person implements Serializable {
public static final long serialVersionUID = 47564635353432L;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
随机存取文件流
1.RandomAccessFile 类既可以作为输入流,又可以做输出流,直接继承于java.lang.Object类。并且它实现了DataInput、DataOutput这两个接口。
2.RandomAccessFile若作为输出流,写出的文件如果不存在,则在执行过程中自动创建,如果写出到的文件存在,则会对原有文件的内容进行覆盖(默认从头覆盖)
RandomAccessFile 类对象可以自由移动记录指针:
long getFilePointer():获取文件记录指针的当前位置
void seek(long pos):将文件记录指针定位到 pos 位置
package com.atguigu.java;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @author ycy
* @create 2020 - 07 -14 -7:42 下午
*/
public class RandomAccessFileTest {
@Test
public void test() {
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile(new File("dang-an.jpg"), "r");
raf2 = new RandomAccessFile(new File("dang-an1.jpg"), "rw");
byte[] bytes = new byte[1024];
int len;
while ((len = raf1.read(bytes)) != -1) {
raf2.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (raf1 != null)
raf1.close();
if (raf2 != null)
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}