Java IO 对字符的读取和写出

1、对字符的读取

只能读取纯文本,不能读取二进制文件如音频,视频等,doc文件以及其他不是纯文本的文档。

1.1 纯文本的读取

使用java.io.Reader类读取纯文本文件,其源代码重要的几个方法如下:

package java.io;
public abstract class Reader implements Readable, Closeable {
    /**
     * 读取一个字符
     */
    public int read() throws IOException {
        char cb[] = new char[1];
        if (read(cb, 0, 1) == -1)
            return -1;
        else
            return cb[0];
    }
    /**
     * 读取一个字符数组
     */
    public int read(char cbuf[]) throws IOException {
        return read(cbuf, 0, cbuf.length);
    }
    /**
     * 读取一个字符数组或者字符数组的一部分
     */
    abstract public int read(char cbuf[], int off, int len) throws IOException;
    /**
     * 关闭流
     */
     abstract public void close() throws IOException;
}

1.2 读取纯文本的demo如下:

/**
 * 
 * @param file
 *            文件对象
 */
public static void readFile(File file) {
    Reader reader = null;
    try {
        reader = new FileReader(file);
        char[] buffer = new char[1024];
        int len = 0;
        while (-1 != (len = reader.read(buffer))) {
            System.out.println(new String(buffer, 0, len));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != reader) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/**
 * 
 * @param file
 *            文件对象
 */
public static void readFileWithJdk7(File file) {
    // java 7 新特性 try-with-resource
    // 不用手动释放资源,程序自动释放,因为Reader实现了AutoCloseable接口
    try (Reader reader = new FileReader(file)) {
        char[] buffer = new char[1024];
        int len = 0;
        while (-1 != (len = reader.read(buffer))) {
            System.out.println(new String(buffer, 0, len));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
/**
 * 
 * @param filePath
 *            文件路径
 */
public static void readFile(String filePath) {
    readFile(new File(filePath));
}

2、对字符的写出

只能对纯文本写出。

2.1 纯文本的写出

使用java.io.Writer类向纯文本进行写出,其中源码几个重要的方法如下:

package java.io;
public abstract class Writer implements Appendable, Closeable, Flushable {
    /**
     * 写一个字符
     */
    public void write(int c) throws IOException {
        synchronized (lock) {
            if (writeBuffer == null){
                writeBuffer = new char[WRITE_BUFFER_SIZE];
            }
            writeBuffer[0] = (char) c;
            write(writeBuffer, 0, 1);
        }
    }
    /**
     * 写一个字符数组
     */
    public void write(char cbuf[]) throws IOException {
        write(cbuf, 0, cbuf.length);
    }
    /**
     *写一个字符数组或字符数组的一部分
     */
    abstract public void write(char cbuf[], int off, int len) throws IOException;

    /**
     * 写一个字符串
     */
    public void write(String str) throws IOException {
        write(str, 0, str.length());
    }
    /**
     * 写一个字符串或字符串的一部分
     */
    public void write(String str, int off, int len) throws IOException {
        synchronized (lock) {
            char cbuf[];
            if (len <= WRITE_BUFFER_SIZE) {
                if (writeBuffer == null) {
                    writeBuffer = new char[WRITE_BUFFER_SIZE];
                }
                cbuf = writeBuffer;
            } else {    // Don't permanently allocate very large buffers.
                cbuf = new char[len];
            }
            str.getChars(off, (off + len), cbuf, 0);
            write(cbuf, 0, len);
        }
    }
    /**
     * 追加特定字符到此流中
     */
    public Writer append(CharSequence csq) throws IOException {
        if (csq == null)
            write("null");
        else
            write(csq.toString());
        return this;
    }
    /**
     * 追加特定字符或特定字符的一部分到此流中
     */
    public Writer append(CharSequence csq, int start, int end) throws IOException {
        CharSequence cs = (csq == null ? "null" : csq);
        write(cs.subSequence(start, end).toString());
        return this;
    }
    /**
     * 追加特定字符到此流中
     */
    public Writer append(char c) throws IOException {
        write(c);
        return this;
    }
    /**
     * 刷新流
     */
    abstract public void flush() throws IOException;
    /**
     * 关闭流
     */
    abstract public void close() throws IOException;
}

2.2 纯文本写出demo如下:

/**
 * jdk 7 新特性
 * 
 * @param file
 *            指定输出文件
 * @param msg
 *            输出内容
 * @param append
 *            是否追加,true 追加 false 不追加
 */
public static void writeToFileWithJdk7(File file, String msg, boolean append) {
    try (Writer writer = new FileWriter(file)) {
        writer.write(msg);
        writer.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
/**
 * 
 * @param file
 *            指定输出文件
 * @param msg
 *            输出内容
 * @param append
 *            是否追加,true 追加 false 不追加
 */
public static void writeToFile(File file, String msg, boolean append) {
    Writer writer = null;
    try {
        writer = new FileWriter(file);
        writer.write(msg);
        writer.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != writer) {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/**
 * 
 * @param filePath
 *            指定输出文件路径
 * @param msg
 *            输出内容
 * @param append
 *            是否追加,true 追加 false 不追加
 */
public static void writeToFile(String filePath, String msg, boolean append) {
    writeToFile(new File(filePath), msg, append);
}
public static String loadAFileToStringDE1(File f) throws IOException { long beginTime = System.currentTimeMillis(); InputStream is = null; String ret = null; try { is = new BufferedInputStream( new FileInputStream(f) ); long contentLength = f.length(); ByteArrayOutputStream outstream = new ByteArrayOutputStream( contentLength > 0 ? (int) contentLength : 1024); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { outstream.write(buffer, 0, len); } outstream.close(); ret = outstream.toString(); //byte[] ba = outstream.toByteArray(); //ret = new String(ba); } finally { if(is!=null) {try{is.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法1用时"+ (endTime-beginTime) + "ms"); return ret; } public static String loadAFileToStringDE2(File f) throws IOException { long beginTime = System.currentTimeMillis(); InputStream is = null; String ret = null; try { is = new FileInputStream(f) ; long contentLength = f.length(); byte[] ba = new byte[(int)contentLength]; is.read(ba); ret = new String(ba); } finally { if(is!=null) {try{is.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法2用时"+ (endTime-beginTime) + "ms"); return ret; } public static String loadAFileToStringDE3(File f) throws IOException { long beginTime = System.currentTimeMillis(); BufferedReader br = null; String ret = null; try { br = new BufferedReader(new FileReader(f)); String line = null; StringBuffer sb = new StringBuffer((int)f.length()); while( (line = br.readLine() ) != null ) { sb.append(line).append(LINE_BREAK); } ret = sb.toString(); } finally { if(br!=null) {try{br.close();} catch(Exception e){} } } long endTime = System.currentTimeMillis(); System.out.println("方法3用时"+ (endTime-beginTime) + "ms"); return ret; } 3个方法去读取一个大于50M的文件,当不设置jvm参数时都OutofMemery,当设置-Xmx128M时。只有方法3 可以通过,设置到-Xmx256M时也只有方法3可以通过,干脆设置512M,都可以了,运行时间如果正常的话一般都在4~5S
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值