JAVA编程问题(BufferedWriter)

好像我每次用BufferedWriter 的方法写入文件的时候都是从头开始写的。怎样才能接着原有文件的信息后面写东西。

如果单纯的原封不动地复制文件的话,直接用InputStream和OutputStream就好了。
这两个类才是面向字节流的。
可以原封不动的复制。
用buffered包一下可以提高效率。
如以下代码可复制文件:
InputStream input = new FileInputStream(sourcefile);

FileOutputStream output = new FileOutputStream(destfile);

BufferedInputStream bis = new BufferedInputStream(input);

BufferedOutputStream bos = new BufferedOutputStream(output);

byte[] byt = new byte[1024];

while (bis.read(byt) != -1) {

bos.write(byt, 0, byt.length);

bos.flush();
}

try {

input.close();
output.close();
bis.close();
bos.close();

} catch (Exception e) {
}

如果用追加的方式有三种方法
public static void method1(String file, String conent) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true)));
out.write(conent);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void method2(String fileName, String content) {
try {
// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void method3(String fileName, String content) {
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
// 将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-06-22
不要用BufferedWriter 换 FileWriter,他的构造函数有一个参数是boolean append,为真就是接着写进去
第2个回答  2012-06-22
new BufferedWriter(new OutputStreamWriter( new FileOutputStream ("文件名",true); true表示追加
第3个回答  2012-06-22
.append

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网