当前位置: 技术问答>java相关
???给分!!!Java中怎样在一个文件尾部添加新内容?
来源: 互联网 发布时间:2015-03-15
本文导语: | public void appendToFile(String str, String filename) throws Exception { // Open up an outputstream writer to the file, and append str to it. FileOutputStream stream;//provides file access OutputStreamWrit...
|
public void appendToFile(String str, String filename) throws Exception
{
// Open up an outputstream writer to the file, and append str to it.
FileOutputStream stream;//provides file access
OutputStreamWriter writer;//writes to the file
try
{
stream = new FileOutputStream(filename, true);
writer = new OutputStreamWriter(stream);
writer.write(str);
writer.close();
stream.close();
}//try
catch(Exception e)
{
throw e;
}//catch
}//appendToFile
{
// Open up an outputstream writer to the file, and append str to it.
FileOutputStream stream;//provides file access
OutputStreamWriter writer;//writes to the file
try
{
stream = new FileOutputStream(filename, true);
writer = new OutputStreamWriter(stream);
writer.write(str);
writer.close();
stream.close();
}//try
catch(Exception e)
{
throw e;
}//catch
}//appendToFile
|
使用构件器:FileOutputStream(String name, boolean append),置布尔值为ture。
|
import java.io.*;
public class TestWrite {
public static void main(String[] args) {
try {
FileReader fr = new FileReader( "c:\aaa.txt" );
String oldCon = "";
int c;
while ( (c = fr.read()) != -1 )
oldCon += (char)c;
fr.close();
FileWriter fw = new FileWriter( "c:\aaa.txt" );
fw.write(oldCon);
fw.write("insert to the file end.");
fw.close();
} catch (Exception e) {
}
}
}
public class TestWrite {
public static void main(String[] args) {
try {
FileReader fr = new FileReader( "c:\aaa.txt" );
String oldCon = "";
int c;
while ( (c = fr.read()) != -1 )
oldCon += (char)c;
fr.close();
FileWriter fw = new FileWriter( "c:\aaa.txt" );
fw.write(oldCon);
fw.write("insert to the file end.");
fw.close();
} catch (Exception e) {
}
}
}
|
可以用java.io.RandomAccessFile
您可能感兴趣的文章:
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。