62,621
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
public class ReadFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader myFileReader=new FileReader("d:/javatest/dsstatic_20090427.f");
BufferedReader myBufferedReader=new BufferedReader(myFileReader);
String myString=null;
String resultString=new String();
while((myString=myBufferedReader.readLine())!=null)
{ System.out.println(myString);
}
myFileReader.close();
}
}
public static void main(String[] args) throws Exception{
//如果a.txt文件中包函 txt 则会把 txt 替换成txt123 ,楼主可试试,看是不是你所想要的那种
String filePath = "c:/tmp/a.txt";
String tmpFile = "c:/tmp/"+System.currentTimeMillis()+".txt";
copyFile(filePath,tmpFile);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tmpFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] b = new byte[1024];
int c =0;
while((c=bis.read(b)) > 0){
String s = new String(b).replaceAll("txt", "txt123");
bos.write(s.getBytes());
}
bis.close();
bos.close();
//删除临时文件
new File(tmpFile).delete();
}
/**复制文件*/
private static void copyFile(String sourceFile,String targetFile)throws Exception{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] by = new byte[1024];
int c=0;
while((c = bis.read(by))> 0){
bos.write(by);
}
bos.close();
bis.close();
}