Java OutputStreamWriter write()方法

java.io.OutputStreamWriter.write(String str, int off, int len) 方法写入字符串的一部分。

1 语法

public void write(String str, int off, int len)

2 参数

str:一个字符串。

off:开始写入字符的偏移量。

len:要写入的字符数。

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.OutputStreamWriter.write(String str, int off, int len) 方法的例子
 */
import java.io.*;

public class Demo {
    public static void main(String[] args) {
        String s = "Hello world!";

        try {
            // create a new OutputStreamWriter
            OutputStream os = new FileOutputStream("test.txt");
            OutputStreamWriter writer = new OutputStreamWriter(os);

            // create a new FileInputStream to read what we write
            FileInputStream in = new FileInputStream("test.txt");

            // write something in the file
            writer.write(s, 0, 5);

            // flush the stream
            writer.flush();

            // read what we write
            for (int i = 0; i < 5; i++) {
                System.out.print("" + (char) in.read());
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

输出结果为:

Hello

热门文章

优秀文章