爬上你的脸和你的胸膛,
有一次在冬天,我也曾经从埃及乘船
还有一只小船艰难地逆流而上。
深色的外套,白色的衣领。干事们不倦地
我们的岁月放在费解的光中,
就在红尘中的流过哈哈
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import org.junit.Test;
public class Demo01 {
@Test
public void test() throws Exception {
RandomAccessFile raf = new RandomAccessFile("bbb.xml", "r");
// 确定文件的读取位置
raf.seek(10);
byte[] buffer = new byte[1024];
int len = 0;
while((len=raf.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len, "utf-8"));
}
raf.close();
}
}
没什么好的办法,无非就是将文档内容读到内存,在程序里将你要做的修改改好了,将原文件清空,再写到原来的文件上
应该先了解java操作txt文件的原理
java把txt文件的内容以流的形式读取出来放到一个“容器”里,然后根据你的需求对这个容器内的内容进行处理,然后再写回到txt中……
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class UpdateTxt {
static List
public static void main(String[] args) {
read("D:/lj/12.txt");
// add(2,"asd");
delete(2);
// addToFinal("asd");
write("D:/lj/12.txt");
}
//读取
public static void read(String path){
String temp = null;
int i = 0;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
while((temp = br.readLine()) != null){
txt.add(temp);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//写回
public static void write(String path){
try {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path)));
for(int i = 0; i
pw.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//添加到第几行
public static void add(int line , String s){
txt.add(line-1, s);
}
//删除某行
public static void delete(int line){
txt.remove(line - 1);
}
//添加到最后
public static void addToFinal(String s){
txt.add(s);
}
}