java txt的指定行改写

用JAVA对txt中指定行数的数据进行改写并且保存在原文件中
比如:
1234
1122
1232141
修改第三行
1234
1122
ashdh

文本文件是没办法直接替换行的,因为文件是连续存储的,每行的长度不同。
只能是改写完这行,再把它后面所有的行重写一次。当然也可以直接在内存中替换了全部再写一次,这样实现起来最简单。

 public static void replaceTxtByLineNo(String path,int lineNo,String newStr) {
        String temp = "";
        try {
            File file = new File(path);
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();

            // 保存该行前面的内容
            for (int j = 1; (temp = br.readLine()) != null; j++) {
                if(j==lineNo){
                    buf = buf.append(newStr);
                }else{
                    buf = buf.append(temp);
                }
                buf = buf.append(System.getProperty("line.separator"));
            }

            br.close();
            FileOutputStream fos = new FileOutputStream(file);
            PrintWriter pw = new PrintWriter(fos);
            pw.write(buf.toString().toCharArray());
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] s) throws IOException {
        replaceTxtByLineNo("D:/test.txt",3,"ashdh222");
    }

可以使用nio的Files API

List<String> lines = Files.readAllLines(Paths.get("文件名"));
List<String> replaced = new ArrayList<>();
int lineNo = 1;

for (String line : lines) {
    if (lineNo % 3 == 0) {
               replaced.add("替换成的行");
        } else {
            replaced.add(line);
        }
        lineNo++;
}
Files.write(Paths.get("文件名"), replaced);

学习了,高手在上面。