代码:
package Filetest;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Test1_CopyFile {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("a.txt");
fos = new FileOutputStream("b.txt");
int i;
while ((i = fis.read()) !=-1){
System.out.println((char)i);
fos.write(i);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(fis != null){
fis.close();
}
}catch (Exception e){
e.printStackTrace();
}
try {
if(fos != null){
fos.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
2. 字节流缓冲区
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test2_CopyFile {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("a.txt");
FileOutputStream fos = new FileOutputStream("b.txt");
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes)) != -1){
fos.write(bytes,0 ,len);
}
fis.close();
fos.close();
}
}
3. 转换流
可以用指定编码表去读取数据,解决乱码问题
读:
package test;
import java.io.*;
public class Demo1_InputStreamReader {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("b.txt"),"utf-8"));
String line = br.readLine();
System.out.println(line);
br.close();
}
}
写:
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Demo2_OutputStreamWriter {
public static void main(String[] args) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("c.txt"),"utf-8");
osw.write("你好你好");
osw.close();
}
}
4. 遍历目录下的文件
IDEA快捷键:
Ctrl + Alt + M ——> 抽取方法
Alt + Shift ——> 转换成Lambda表达式
输入iter + Tab ——> 生成foreach代码
package test;
import java.io.File;
import java.util.Arrays;
public class FileMethod {
public static void main(String[] args) {
printFile(new File("E:\课本"));
}
//递归遍历文件夹:获取一个文件夹下所有的文件名称,包含子文件夹
public static void printFile(File dir){
//1. 获取传入文件夹下的所有文件和文件夹对象
File[] files =dir.listFiles();
//2. 遍历数组,获取每一个文件和文件夹对象
for (File file : files) {
if (file.isFile()){
System.out.println(file.getName());
}else if (file.isDirectory()){
if (file.listFiles() != null){
printFile(file);
}
}
}
}
private static void method2() {
File f = new File("E:");
if (f.isDirectory()){
String[] sArr = f.list((dir, name) -> name.endsWith(".txt"));
Arrays.stream(sArr).forEach(System.out::println);
}
}
private static void method1() {
File f = new File("E:");
if (f.isDirectory()){
String[] sArr = f.list();
Arrays.stream(sArr).forEach(System.out::println);
}
}
}
5. RandomAccessFile类
package test;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test_raf {
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile("config.txt","rw");
int num = Integer.parseInt(raf.readLine())-1;
if (num > 0){
System.out.println("您还有"+ num + "次使用机会");
raf.seek(0);
raf.write((num+"").getBytes());
}else {
System.out.println("您的使用次数已到达上限,请购买正版");
}
raf.close();
}
}
6. 对象序列化
package test;
import java.io.*;
public class Demo1_ObjectStream {
public static void main(String[] args) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));
Object object = ois.readObject();
System.out.println(object);
}
private static void method() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt"));
Person p = new Person("张三",23);
oos.writeObject(p);
oos.close();
}
}
package test;
import java.io.Serializable;
public class Person implements Serializable {
private static final long seriaLVersionUID = 1L;
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
}
7. NIO
Buffer:
Buffer缓冲器: 底层就是一个数组,主要用于和Channel通道配合,完成数据的传输 Buffer是一个抽象类,抽象类不能直接new对象,需要使用其子类 ByteBuffer ShortBuffer IntBuffer LongBuffer FloatBuffer DoubleBuffer CharBuffer 注意:子类不能使用new对象,需要通过allocate方法去创建 capacity : 容量 limit : 可以操作到哪个索引(界限) position : 当前准备操作的索引 mark : 标记,用来记录当前position的值 reset : 如果position的值发生了变化,那么通道随reset可以反馈记录的那个值
import java.nio.ByteBuffer;
public class ExDemo {
public static void main(String[] args) {
//创建一个容器
ByteBuffer buffer = ByteBuffer.allocate(1024);
System.out.println("缓冲器的容量:"+buffer.capacity());
System.out.println("界限:"+ buffer.limit());
System.out.println("索引:"+ buffer.position());
System.out.println("----------------------------------");
//向容器中存数据
buffer.put("abcde".getBytes());
System.out.println("缓冲器的容量:"+buffer.capacity());
System.out.println("界限:"+ buffer.limit());
System.out.println("索引:"+ buffer.position());
System.out.println("----------------------------------");
//切换读写模式
buffer.flip();
System.out.println("缓冲器的容量:"+buffer.capacity());
System.out.println("界限:"+ buffer.limit());
System.out.println("索引:"+ buffer.position());
System.out.println("----------------------------------");
//读数据
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes);
System.out.println(new String(bytes));
System.out.println("缓冲器的容量:"+buffer.capacity());
System.out.println("界限:"+ buffer.limit());
System.out.println("索引:"+ buffer.position());
System.out.println("----------------------------------");
}
}
Channel:
方式1:
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ExDemo {
public static void main(String[] args) throws IOException {
// 1.创建输入输出流对象
FileInputStream fis = new FileInputStream("E:\a.flv");
FileOutputStream fos = new FileOutputStream("D:\b.flv");
// 2.获取输入和输出的通道
FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.getChannel();
// 3.创建缓冲器
ByteBuffer buffer = ByteBuffer.allocate(1024);
while ((inChannel.read(buffer)) != -1){
//切换读写模式
buffer.flip();
outChannel.write(buffer);
buffer.clear();
}
inChannel.close();
outChannel.close();
fis.close();
fos.close();
}
}
方式2:
import java.io.*;
import java.nio.channels.FileChannel;
public class ExDemo {
public static void main(String[] args) throws IOException {
RandomAccessFile infile = new RandomAccessFile("D:\a.flv","rw");
RandomAccessFile outfile = new RandomAccessFile("E:\a.flv","rw");
// 1.获取通道
FileChannel inChannel = infile.getChannel();
FileChannel outChannel = outfile.getChannel();
long num = inChannel.transferTo(0,inChannel.size(),outChannel);
if (num > 0){
System.out.println("复制成功!");
}
infile.close();
outfile.close();
inChannel.close();
outChannel.close();
}
}
Path
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ExDemo {
public static void main(String[] args) throws IOException {
// 1.获取Path对象
Path path = Paths.get("D:\abc\a.fle");
// 2.获取Path对象中的信息
System.out.println(path.getRoot()); //获取根路径
System.out.println(path.getParent()); //获取父路径
System.out.println(path.getNameCount()); //path中的路径名称数
for (int i = 0; i 获取路径名称
Path name = path.getName(i);
System.out.println(name);
}
System.out.println(path.toAbsolutePath()); //绝对路径
System.out.println(path.toUri()); //网络资源定位符
}
}
Files
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
public class ExDemo {
public static void main(String[] args) throws IOException {
Path path = Paths.get("E:\abc\test");
// 1.createDirectories:创建多级文件夹
Files.createDirectories(path);
// 2.createFile:创建文件
Path filePath = Paths.get("E:\abc\test\aaa.txt");
Files.createFile(filePath);
// 3.write:将文本行写入文件,并传入指定的写入模式
ArrayList list = new ArrayList<>();
list.add("这是第一行文本1");
list.add("这是第一行文本2");
list.add("这是第一行文本3");
Files.write(filePath,list, StandardOpenOption.APPEND);
// 4.readAllLines:从文件中读取所有的行
List list1 = Files.readAllLines(filePath);
System.out.println(list1);
// 5.sizi:返回文件的大小,以字节为单位
long size = Files.size(filePath);
System.out.println(size);
}
}



