package com.tij.io.file;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
/**
* 追加内容到文件中
* @author GYJ
* @date 2014-3-22
*/
public class AppendFile {
/**
* 之前写了如何写入文件,单是写入文件是覆盖了之前的内容
* <p>这个实例展现如何追加内容到文件中
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//追加的目标文件
String fileName = "/Users/GYJ/java1.txt";
//追加的数据
String appendData = "this string will be append to last row fileName";
//追加文件
addpendUsingOutputStream(fileName, appendData);
appendUsingBufferedWrite(fileName, appendData, 400);
appendUsingFileWrite(fileName, appendData);
//读出文件
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, Charset.defaultCharset());
BufferedReader br = new BufferedReader(isr);
String line;
int i = 0;
while ((line = br.readLine()) != null) {
i ++;
System.out.println(i + "read result = " + line);
}
br.close();
}
/**
* 使用普通流
* @param fileNme 被追加的文件名称
* @param data 被追加的数据内容
* @throws IOException
*/
private static void addpendUsingOutputStream(String fileName, String data) throws IOException {
//true: 表示是追加的标志
FileOutputStream os = new FileOutputStream(new File(fileName), true);
os.write(data.getBytes(), 0, data.length());
os.close();
}
/**
* 使用BufferedWrite
* @param fileName
* @param data
* @throws IOException
*/
private static void appendUsingBufferedWrite(String fileName, String data, int noOfLines) throws IOException {
File file = new File(fileName);
FileWriter fw = null;
BufferedWriter bw = null;
//true:表示是追加的标志
fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
//开始输出写入文件
for (int i = 0; i < noOfLines; i++) {
bw.newLine();
fw.write(data);
}
bw.close();
fw.close();
}
/**
* 使用fileWrite
* @param fileName
* @param data
* @throws IOException
*/
private static void appendUsingFileWrite(String fileName, String data) throws IOException {
File file = new File(fileName);
FileWriter fw = null;
//true:表示是追加的标志
fw = new FileWriter(file, true);
fw.write(data);
fw.close();
}
}
17、java追加文件内容(写入方式)
最新推荐文章于 2024-06-30 03:39:49 发布