读取写入文本文件

前端之家收集整理的这篇文章主要介绍了读取写入文本文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
publicclassReadWriteFile{
publicBufferedReaderbufread;
publicBufferedWriterbufwriter;
Filewritefile;
Stringfilepath,filecontent,read;
StringreadStr="";
//从文本文件中读取内容
publicStringread(Stringpath)
{
try{
filepath=path;//得到文本文件的路径
Filefile=newFile(filepath);
FileReaderfileread=newFileReader(file);
bufread=newBufferedReader(fileread);
while((read=bufread.readLine())!=null){
read=read+"/r/n";
readStr=readStr+read;
}
}catch(Exceptiond){
System.out.println(d.getMessage());
}
returnreadStr;//返回从文本文件中读取内容
}
//向文本文件中写入内容
publicvoidwrite(Stringpath,Stringcontent,booleanappend){
try{
booleanaddStr=append;//通过这个对象来判断是否向文本文件中追加内容
filepath=path;//得到文本文件的路径
filecontent=content;//需要写入的内容
writefile=newFile(filepath);
if(writefile.exists()==false)//如果文本文件不存在则创建它
{
writefile.createNewFile();
writefile=newFile(filepath);//重新实例化
}
FileWriterfilewriter=newFileWriter(writefile,addStr);
//删除原有文件内容
java.io.RandomAccessFilefile=newjava.io.RandomAccessFile(path,"rw");
file.setLength(0);
//写入新的文件内容
filewriter.write(filecontent);
filewriter.close();
filewriter.flush();
}catch(Exceptiond){
System.out.println(d.getMessage());
}
}
publicstaticvoidmain(String[]args)throwsException{
ReadWriteFilert=newReadWriteFile();
Stringfilecontent=rt.read("c:/test.xml");
rt.write("c:/test.xml",true);
}
}
原文链接:https://www.f2er.com/xml/298567.html

猜你在找的XML相关文章