、使用字符流,读取和存储纯文本文件。
存储文件,也就是像一个文件里写内容,既然是写,那就需要使用输出流。而且我们写的是纯文本文件,所以这里使用字符流来操作,Java api提供给我们FileWriter这么一个类,我们来试试:(读取文件同理使用FileReader类)
- package org.example.io;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- public class TestFileWriter {
- public static void main(String[] args) throws Exception {
- writeToFile();
- readFromFile();
- }
- /**
- * DOC 从文件里读取数据.
- *
- * @throws FileNotFoundException
- * @throws IOException
- */
- private static void readFromFile() throws FileNotFoundException, IOException {
- File file = new File("E:\\helloworld.txt");// 指定要读取的文件
- FileReader reader = new FileReader(file);// 获取该文件的输入流
- char[] bb = new char[1024];// 用来保存每次读取到的字符
- String str = "";// 用来将每次读取到的字符拼接,当然使用StringBuffer类更好
- int n;// 每次读取到的字符长度
- while ((n = reader.read(bb)) != -1) {
- str += new String(bb, 0, n);
- }
- reader.close();// 关闭输入流,释放连接
- System.out.println(str);
- }
- /**
- * DOC 往文件里写入数据.
- *
- * @throws IOException
- */
- private static void writeToFile() throws IOException {
- String writerContent = "hello world,你好世界";// 要写入的文本
- File file = new File("E:\\helloworld.txt");// 要写入的文本文件
- if (!file.exists()) {// 如果文件不存在,则创建该文件
- file.createNewFile();
- }
- FileWriter writer = new FileWriter(file);// 获取该文件的输出流
- writer.write(writerContent);// 写内容
- writer.flush();// 清空缓冲区,立即将输出流里的内容写到文件里
- writer.close();// 关闭输出流,施放资源
- }
- }
测试结果:
hello world,你好世界
二、使用字节流,读取和存储图片
首先使用输入流读取图片信息,然后通过输出流写入图片信息:
- package org.example.io;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- public class TestIOStream {
- /**
- *
- * DOC 将F盘下的test.jpg文件,读取后,再存到E盘下面.
- *
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- FileInputStream in = new FileInputStream(new File("F:\\test.jpg"));// 指定要读取的图片
- File file = new File("E:\\test.jpg");
- if (!file.exists()) {// 如果文件不存在,则创建该文件
- file.createNewFile();
- }
- FileOutputStream out = new FileOutputStream(new File("E:\\test.jpg"));// 指定要写入的图片
- int n = 0;// 每次读取的字节长度
- byte[] bb = new byte[1024];// 存储每次读取的内容
- while ((n = in.read(bb)) != -1) {
- out.write(bb, 0, n);// 将读取的内容,写入到输出流当中
- }
- out.close();// 关闭输入输出流
- in.close();
- }
- }