原文出处:http://mrwlh.blog.51cto.com/2238823/1093524
一、使用字符流,读取和存储纯文本文件。
存储文件,也就是像一个文件里写内容,既然是写,那就需要使用输出流。而且我们写的是纯文本文件,所以这里使用字符流来操作,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();
- }
-
-
-
-
-
-
-
- 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 = "";
- int n;
- while ((n = reader.read(bb)) != -1) {
- str += new String(bb, 0, n);
- }
- reader.close();
- System.out.println(str);
- }
-
-
-
-
-
-
- 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 {
-
-
-
-
-
-
-
-
- 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();
- }
-
- }