Java从文本文件读取_向文本文件写入数据

通过Java从文本文件读取和向文本文件写入数据,了解流的基本的常用的方法。


示例代码:

package iotest;

import org.junit.Test;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: ASUS
 * Date: 14-7-21
 * Time: 下午6:49
 * To change this template use File | Settings | File Templates.
 */
public class IOTest {


    /**
     * 使用InputStream从文本文件中读取数据到ByteArrayOutputStream输出流中
     * ByteArrayOutputStream
     */
    @Test
    public void test() throws IOException {

        String filePath = this.getClass().getResource("/iotest/hello.txt").getFile();
        File file = new File(filePath);
        InputStream inputStream = new FileInputStream(file);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int b;
        while ((b = inputStream.read()) != -1) {
            if (b == 10) {
                System.out.println("new line");
            }
            bos.write(b);
        }
        byte[] result = bos.toByteArray();
        System.out.println(new String(result));
    }

    /**
     * 使用BufferedInputStream从文本文件读取数据
     * BufferedInputStream
     * 创建BufferedInputStream时,我们会通过它的构造函数指定某个输入流为参数。
     * BufferedInputStream会将该输入流数据分批读取,
     * 每次读取一部分到缓冲中;操作完缓冲中的这部分数据之后,再从输入流中读取下一部分的数据。
     *
     * @throws FileNotFoundException
     */
    @Test
    public void test9876() throws IOException {
        int buffer_size = 12;   //每次缓冲12个字节(做实验)
        String filePath = this.getClass().getResource("/iotest/hello.txt").getFile();
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(filePath), buffer_size);
        System.out.println(in.available());//45(可以读取到的总的字节数)

        in.mark(50); //50为最大读取的字节的数量,当超过此数量后,mark失效
        byte[] data = new byte[40];    //只读取40个字节
        in.read(data);
        System.out.println(new String(data));

        byte[] data2 = new byte[5];
        in.read(data2);    //读取剩余的5个字节
        System.out.println(new String(data2));

        in.reset(); //重置此流

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] data3 = new byte[5];
        while (in.read(data3) != -1) {
            bos.write(data3);
        }
        System.out.println(bos.toString());
    }


    /**
     * 使用BufferedReader从文本文件中读取数据(缓冲输入流)
     * BufferedReader
     * InputStreamReader
     *
     * @throws IOException
     */
    @Test
    public void test2323() throws IOException {
        String filePath = this.getClass().getResource("/iotest/hello.txt").getFile();
        File file = new File(filePath);
        InputStreamReader read = new InputStreamReader(new FileInputStream(file));
        BufferedReader bufferedReader = new BufferedReader(read);
        String line = null;
        StringBuilder builder = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            builder.append(line);     //缓存读到的数据
        }
        System.out.println(builder.toString());  //打印出的数据没有换行(没有读取换行符)
    }


    /**
     * ByteArrayInputStream
     * 把字节数组转换为字节流对象,以便提供读取接口read方法
     * read()的作用是从字节流中“读取下一个字节”。
     * read(byte[] buffer, int offset, int length)的作用是从字节流读取字节数据,并写入到字节数组buffer中。
     */
    @Test
    public void test23233() {
        byte[] ArrayLetters = {
                0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
                0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
        };

        ByteArrayInputStream bais = new ByteArrayInputStream(ArrayLetters);
        int LEN = 5;
        for (int i = 0; i < LEN; i++) {
            // 若能继续读取下一个字节,则读取下一个字节
            if (bais.available() >= 0) {
                // 读取“字节流的下一个字节”
                int tmp = bais.read();
                System.out.printf("%d : 0x%s\n", i, Integer.toHexString(tmp));
            }
        }
    }

    /**
     * 使用FileWriter向文本文件中写入数据
     * windows中\r\n换行
     *
     * @throws IOException
     */
    @Test
    public void test8766() throws IOException {
        String filePath = this.getClass().getResource("/iotest/hello2.txt").getFile();
        //直接调用构造方法,传递写入路径。FileWriter类的构造方法有五个。
        FileWriter writer = new FileWriter(filePath);
        //FileWriter类的Write()方法向文件中写入字符。
        writer.write("Hello!\r\n");
        writer.write("Thisis my first text file,\r\n");
        writer.write("I'mvery happy!\r\n");
        writer.write("EveryDay is a new Day!\r\n");
        writer.write("我爱我家!");
        writer.close();
    }

    /**
     * 使用BufferedWriter向文本文件中写入数据
     * windows中\r\n换行
     *
     * @throws IOException
     */
    @Test
    public void test87a6() throws IOException {
        String filePath = this.getClass().getResource("/iotest/hello2.txt").getFile();
        BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
        //FileWriter类的Write()方法向文件中写入字符。
        out.write("NewHello!");
        out.newLine();
        out.write("This is Buffer Writer范例,");
        out.newLine();
        out.write("keepalone");
        out.newLine();
        out.close();
    }

    /**
     * 使用OutputStream想文本文件写入数据
     *
     * @throws IOException
     */
    @Test
    public void test87559() throws IOException {
        String filePath = this.getClass().getResource("/iotest/hello2.txt").getFile();
        OutputStream out = new FileOutputStream(filePath);
        out.write("abcdefg".getBytes());
        out.write("\r\n".getBytes());  //换行
        out.write("123456".getBytes());
    }

    /**
     * OutputStreamWriter包装字节流输出流
     * 向文本文件写入数据
     *
     * @throws IOException
     */
    @Test
    public void test86() throws IOException {
        String filePath = this.getClass().getResource("/iotest/hello2.txt").getFile();
        OutputStream out = new FileOutputStream(filePath);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out);   //字节流和字符流的转换
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
        bufferedWriter.write("NewHello!");
        bufferedWriter.newLine();
        bufferedWriter.write("This is Buffer Writer范例,");
        bufferedWriter.newLine();
        bufferedWriter.write("keepalone");
        bufferedWriter.newLine();
        bufferedWriter.close();
    }
}

参考:http://www.cnblogs.com/skywang12345/p/io_12.html

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

    /**
     * Prints some data to a file
     */
    public void writeToFile(String filename) {

        BufferedOutputStream bufferedOutput = null;

        try {

            //Construct the BufferedOutputStream object
            bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));

            //Start writing to the output stream
            bufferedOutput.write("Line one".getBytes());
            bufferedOutput.write("\n".getBytes()); //new line, you might want to use \r\n if you're on Windows
            bufferedOutput.write("Line two".getBytes());
            bufferedOutput.write("\n".getBytes());

            //prints the character that has the decimal value of 65
            bufferedOutput.write(65);

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedOutputStream
            try {
                if (bufferedOutput != null) {
                    bufferedOutput.flush();
                    bufferedOutput.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().writeToFile("myFile.txt");
    }
}


===========================END===========================


你可能感兴趣的:(Java从文本文件读取_向文本文件写入数据)