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

用指针定位修改位置 读取时候遇到换行符停止
2024-12-13 20:55:34
推荐回答(1个)
回答1:

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();
}
}