你好,我现在有一个txt文件,想用JAVA编写程序读取其中某一行并做修改,并存为另一个文件

用指针定位修改位置 读取时候遇到换行符停止

第1个回答  推荐于2016-06-08
package textcut;

import java.io.*;

//截取文件中指定的内容
public class TxtCut {
private File textFile;
private BufferedWriter out;
private int num = 3; //截取的行标
public TxtCut() {
textFile = new File("e:/text.txt");// 指定源文件路径
try {
//存储路径
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(
"e:/txtcut.txt"))));
cut(textFile,num);
out.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 读取文件内容并截取需要内容
public void cut(File file,int n) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
String str = "";
while(n-->0){
str = in.readLine();
}
/*
* 可在此处对str进行修改
*/
out.write(str + "\r\n");
System.out.print("操作完成!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new TxtCut();
}
}追问

非常感谢,但我可能没把问题描述清楚,我的意思是读取并修改txt文件某一行,比如说原来第三行内容是“非诚感谢”,想把它替换成“Thank you”并保存,保存的还是原来的文件,其他地方不动

首先一行一行的读取文件readline(),然后到特定的一行,修改这一行,然后再保存回文件

追答

因为我目前还没有见过既能读又能写的数据流,所以我的方法是:先把整个文件读入输入流,然后逐行读取作适当的修改,再写进输出流,最后写入文件!代码就是把cut()方法作一下修改:
// 读取文件内容并作适当修改
public void cut(File file,int n) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
String str = in.readLine();
while(str!=null){
if(--n==0)
out.write("Thank you!"+"\r\n");
else
out.write(str + "\r\n");
str = in.readLine();
}
in.close();
System.out.print("操作完成!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

本回答被网友采纳
相似回答