本例以Windows, JDK1.7 为基础,这里使用BufferedWriter这个类来,对文件写入操作。
BufferedWriter 写入文件的操作,主要有以下方式:
1 2 3 4 5 6
| void write(int c); void write(String s, int off, int len); void write(char[] cbuf, int off, int len)
void write(char[] cbuf); void write(String str);
|
更多关于BufferedWriter的用法可以参考API文档:http://docs.oracle.com/javase/7/docs/api/
文件写入代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| package com.devnp.io;
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException;
public class FileWriteBufferedWriter {
public static void main(String[] args) throws IOException { write(); } public static void write() throws IOException{ File file = new File("D:\\Person-Test\\1.txt"); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file)); String str = "Hi, Hello, I'm devnp.com" ; bufferedWriter.write(str.toCharArray()); bufferedWriter.write(65); bufferedWriter.write(str.toCharArray(), 0, str.length()); bufferedWriter.write(str); bufferedWriter.write(str, 0, str.length()); bufferedWriter.close(); }
}
|
查看写入文件的内容:
D:\Person-Test\1.txt
Hi, Hello, I'm devnp.comAHi, Hello, I'm devnp.comHi, Hello, I'm devnp.comHi, Hello, I'm devnp.com
Author:
Darren Du
License:
Copyright (c) 2019 MIT LICENSE