Java IO实现文件的读写应用

154 阅读3分钟

今天我们来聊聊关于Java IO实现文件的读写应用,随着互联网时代的来临,文件处理已经成为日常开发中非常常见的操作。而对文件的读写往往也就是程序和外部数据交互的媒介。作为Java开发人员,掌握IO和NIO是基础之一。

一、输入流与输出流

Java IO操作文件分为输入流和输出流,输入流用于读取文件,输出流用于写入文件:

// 读取文件
FileInputStream fis = new FileInputStream("file.txt");

// 写入文件  
FileOutputStream fos = new FileOutputStream("file.txt");

二、缓冲输入/输出流

为了提高读写效率,可以添加缓冲区:

BufferedInputStream bis = new BufferedInputStream(fis);

BufferedOutputStream bos = new BufferedOutputStream(fos);

三、字符流

对字符串进行读写时使用字符流:

BufferedReader br = new BufferedReader(new FileReader("file.txt"));

BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"));

四、对象流

用对象流可以直接写入和读取对象或序列化类:

ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);

ObjectInputStream ois = new ObjectInputStream(bis);  
Object obj = ois.readObject();

五、IO操作封装

可以封装IOHelper类进行通用读写:

public static void writeString(String str, File file) throws IOException {
  //...
}

六、文件复制

使用输入和输出流可以实现文件复制:

public static void copyFile(File src, File dest){

  InputStream in = new FileInputStream(src);
  OutputStream out = new FileOutputStream(dest);

  byte[] buffer = new byte[1024];
  int len;
  while((len = in.read(buffer)) > 0){
    out.write(buffer, 0, len);
  }

  in.close();
  out.close();
}

七、文件排序

使用内存排序重写文件内容:

List<String> lines = Files.readAllLines(Path);
lines.sort(Comparator.naturalOrder());
Files.write(Path, lines);

八、文件分块读取

大文件可以通过分块进行高效读取:

byte[] bytes = new byte[1024];
int readLen;
while((readLen = bis.read(bytes)) != -1){
  // 处理字节块
}  

九、NIO非阻塞IO

NIO提供了高效的非阻塞式文件通道操作:

FileChannel channel = FileChannel.open(path);
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);

十、文件读写应用场景

  1. 日志文件写入与追加

  2. 常用配置文件读写

  3. 大文件分段下载/上传

  4. 文本替换与行删除

  5. 图片/视频文件读取显示

来看看具体代码:

// 日志文件写入
FileWriter writer = new FileWriter("log.txt", true);
writer.write("log message");

// properties文件读写
Properties prop = new Properties();
prop.load(new FileInputStream("config.properties")); 

// 大文件分段 
RandomAccessFile file = new RandomAccessFile("bigfile", "rw");
file.read(buffer, pos, len);

// 文本替换
String oldString = "hello";
String newString = "world";
...

// 图片文件读取
BufferedImage image = ImageIO.read(new File("1.png"));

十一、NIO2文件操作

Java7增加了NIO.2提供更强大的文件系统支持:

// 遍历文件树
Files.walkFileTree(path, options, 1, new SimpleFileVisitor<>());

// 文件移动、复制、删除
Files.move(source, target);

Java提供了丰富的IO和NIO streams API来完成文件读写任务。不仅有基础的输入输出流,也有针对不同场景的衍生流,比如缓冲流、对象流等。同时,NIO与NIO2提供了高效的非阻塞IO能力。而在实际应用中,这些API可以用于日常日志记录、配置管理、大文件传输等多种开发场景。只要熟练掌握了文件读写的方法和思路,就可以方便地搭建程序与外部数据的互动桥梁,可以帮助大家在实际项目开发中更好地利用Java IO和NIO进行文件处理。