17、java追加ファイル内容(書き込み方式)
2977 ワード
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();
}
}