我想将一些数据存储在一个文件中。文件的内容将不断增加,因此我需要将数据附加到该文件。
FileOperation.java
package com.chinmay.callblocker;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
/**
* Created by user on 11/11/2014.
*/
public class FileOperation {
public Boolean write(String file_name, String content) {
try {
String file_path = "/sdcard/"+file_name+".txt";
File file = new File(file_path);
if(!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
/*FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.append(content);
osw.close();
fos.close();*/
bw.append(content);
bw.append("\n");
bw.close();
return true;
} catch(IOException e) {
e.printStackTrace();
return false;
}
}
}
我在文件中使用追加但仍然只覆盖。
答案 0 :(得分:0)
private static void writeTobriad2(String text) {
try {
File file = null;
file = new File("D:\\somefolder\\filename.txt");
int kb = 1024;
int mb = 1024 * 1024;
//Getting the runtime reference from system
Runtime runtime = Runtime.getRuntime();
long minimum = 10;
long memory = runtime.freeMemory() / kb;
if (memory < minimum) {
System.out.println(
"##### Heap utilization statistics [MB] #####");
//Print used memory
System.out.println("Used Memory:" +
((runtime.totalMemory() - runtime.freeMemory()) / mb));
//Print free memory
System.out.println("Free Memory:" +
(runtime.freeMemory() / mb));
//Print total available memory
System.out.println("Total Memory:" +
(runtime.totalMemory() / mb));
//Print Maximum available memory
System.out.println("Max Memory:" +
(runtime.maxMemory() / mb));
//System.out.println("Thread in sleep for 2 mins"+new Date());
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("Thread awake after 2 mins"+new Date());
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(text);
bw.newLine();
bw.flush();
bw.close();
fw.close();
//System.out.println("Done");
//TODO Auto-generated method stub
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}