- File的创建及其基本使用方法
public class FileTest {
public static void main(String[] args) throws IOException {
java.io.File f = new java.io.File("D:\\demo.txt");
System.out.println("当前文件是:" +f);
//文件是否存在
System.out.println("判断是否存在:"+f.exists());
//是否是文件夹
System.out.println("判断是否是文件夹:"+f.isDirectory());
//是否是文件(非文件夹)
System.out.println("判断是否是文件:"+f.isFile());
//文件长度
System.out.println("获取文件的长度:"+f.length());
//文件最后修改时间
long time = f.lastModified();
Date d = new Date(time);
System.out.println("获取文件的最后修改时间:"+d);
//设置文件修改时间为1970.1.1 08:00:00
f.setLastModified(0);
//文件重命名
File f2 =new File("d:/test.txt");
f.renameTo(f2);
System.out.println("Rename successfully~");
}
}
- 输入字节流
public class FileInputStreamTest {
public static void main(String[] args) {
File f = new File("D:\\test.txt");
try(FileInputStream fis = new FileInputStream(f);) {
byte[] all = new byte[(int)f.length()];
fis.read(all);
for (var tt:all) {
System.out.println(tt);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 输出字节流
public class FileOutputStreamTest {
public static void main(String[] args) {
File f = new File("D:\\Demo.txt");
try {
FileOutputStream fos = new FileOutputStream(f);
byte[] data = {97, 98};
fos.write(data);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 输入字符流
public class FileReaderTest {
public static void main(String[] args) {
File f = new File("D:\\test.txt");
try (FileReader fr = new FileReader(f)) {
// 创建字符数组,其长度就是文件的长度
char[] all = new char[(int) f.length()];
// 以字符流的形式读取文件所有内容
fr.read(all);
for (char b : all) {
// 打印出来是A B C
System.out.println(b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 输出字符流
public class FileWriterTest {
public static void main(String[] args) {
File f = new File("D:\\test2.txt");
try(FileWriter fr = new FileWriter(f)) {
// 以字符流的形式把数据写入到文件中
String data="abcde456agawag890";
char[] cs = data.toCharArray();
fr.write(cs);
} catch (IOException e) {
e.printStackTrace();
}
}
}
**
总结
字符流与字节流的区别
字节流操作的基本单元为字节;字符流操作的基本单元为Unicode码元。
字节流默认不使用缓冲区;字符流使用缓冲区(JVM内存)。
字节流通常用于处理二进制数据,例如图片、音频、字节数组等
字符流通常处理文本数据,它支持写入及读取Unicode码元,例如汉字等
**