BufferedWriter
将文本写入字符输出流,缓冲字符,以便有效地写入单个字符,数组和字符串,
建议将BufferedWriter封装在任何写操作可能比较花费的Writer周围,例如FileWriters和 OutputStreamWriters
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
将PrintWriter的输出缓冲到文件。在没有缓冲的情况下,每次调用print()方法都会导致字符被转换成字节,
这些字节将被立即写入文件,这可能非常效率低下。
CharArrayWriter
该类实现了一个字符缓冲区,该缓冲区可用作写入器。当数据写入流时,缓冲区会自动增长。
可以使用toCharArray()和toString()检索数据。*<P>*注意:对该类调用CLOSE()没有任何效果,
并且可以在流关闭之后调用该类的方法,而无需生成IOException
FilterWriter
抽象类
用于编写过滤的字符流的抽象类。FilterWriter本身提供了将所有请求传递给包含的流的默认方法。
FilterWriter的子类应该覆盖这些方法中的一些,并且还可以提供其他方法和字段。
OutputStreamWriter
输出流写入器是从字符流到字节流的桥梁。写入到它的字符使用指定的编码为字节。
要获得最高效率,可以考虑封装OutputStreamWriter
在BufferedWriter,以避免频繁的转换器调用
Writer out = new BufferedWriter(new OutputStreamWriter(System.out))
FileWriter
OutputStreamWriter的子类
用于编写字符文件的便捷类。 这个类的构造者
假定默认字符编码和默认字节缓冲区大小是可接受的。 要自己指定这些值,请在FileOutputStream上构造
OutputStreamWriter
文件是否可用或是否可以创建取决于底层平台。 特别是某些平台允许文件,
仅通过一个 FileWriter (或其他write 对象)打开一次。 在这种情况下,这个类中的构造函数
如果涉及的文件已经打开,将失败。
FileWriter 用于编写字符流。
要编写原始字节流,请考虑使用FileOutputStream
PipedWriter
管道字符输出流
PrintWriter
将对象的格式化表示形式打印到文本输出流 它不包含用于写入原始字节的方法,对于这些方法,程序应该使用未编码的字节流
StringWriter
在字符串缓冲区中收集其输出的字符流,然后可用于构造字符串。 关闭StringWriter无效。 在关闭流之后可以调用此类中的方法,而不会生成IOException
Extra
向文件换行写入和追加写入的方式
public static void appendByPaht(String path,String content){
FileOutputStream fos = null;
path = "D:/HH.txt";
content= "12323";
try {
fos = new FileOutputStream(path,true); //true不覆盖已有内容
fos.write(content.getBytes());//写入
//换行符 Windows \r\n, Unix \n ,Java 推荐使用,具有良好的跨平台性 System.getProperty("line.separator")
fos.write("\r\n".getBytes());//换行
fos.write(content.getBytes());
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void appendByBuffer(String path,String content){
path = "D:/HH.txt";
content= "456";
try {
BufferedWriter bf = new BufferedWriter(new FileWriter(path,true));
bf.write(content);
bf.flush();
bf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void appendBybuffer(String path, String content) {
BufferedWriter out = null;
path = "D:/HH.txt";
content= "789";
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path, true)));
out.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void writeRandomFile(String fileName, String content) {
fileName = "D:/HH.txt";
content= "987哈哈哈";
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
// 将写文件指针移到文件尾。
randomFile.seek(fileLength);
String s2=new String(content.getBytes("GBK"),"iso8859-1");
randomFile.writeBytes(s2);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}