package com.dzg.utils;
import java.io.*;
/**
* 流可以分为字符流(以---der结尾的类)和字节流(以Stream结尾的类)
*
* 二者的主要区别:
* 1)字节流读取数据时,读到一个字节就返回一个字节;
* 字符流使用了字节流读到一个或者多个字节时(中文=2字节,UTF-8编码时=3字节),
* 先去查找指定的编码表,将查到的字符返回
* 2)字节流可以处理所有数据类型;
* 字符流只能处理字符数据
* 注意:在处理纯文本数据的时候,优先考虑使用字符流,除此之外都用字节流
*/
public class WriteStreamToFileUtil {
/**
* 使用FileWriter 追加文件
* 测试成功
* @param fileName
* @param content
*/
public static void methodFileWriter(String fileName,String content) {
FileWriter writer = null;
try {
writer = new FileWriter(fileName,true);
writer.write(content+"\r\n");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void methodRandomAccessFile(String fileName,String content){
RandomAccessFile raf = null;
try {
//打开一个随机文件访问流,以读写方式
raf = new RandomAccessFile(fileName,"rw");
//文件长度,字节数
long fileLength = raf.length();
//将文件指针指向文件末尾
raf.seek(fileLength);
raf.writeBytes(content);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param fileName
* @param content
*/
public static void methodBufferedWriter(String fileName,String content) {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName,true)));
bufferedWriter.write(content+"\r\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}