用Java在文件中写入第xth行 [英] write xth row in file in Java

查看:60
本文介绍了用Java在文件中写入第xth行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,假设我有一个n行的文本文件,是否可以只写和替换x行?还是重写所有行以编辑任何行?

in Java, suppose I have a text file with n rows, is it possible to only write and replace row x? or do I rewrite all the rows in order to edit any row?

似乎我已经使用RandomAccess File读取x-1行,然后调用

It seems that I have use RandomAccess File to read x-1 lines, and then call


f.writeChars(str+"\n");

这项工作吗?但它也不会删除现有的第x行.

would this work? but also it won't delete the existing xth line..

推荐答案

如果不更改行长,则可以简单地覆盖原始数据.

If you're not changing the line length, you can simply overwrite the original data.

如果您需要更改行长,或在文件中间添加(或删除)一行,则需要重写从该点到结尾的所有数据.

If you need to change the line length, or add (or remove) a row in the middle of the file, then you need to rewrite all the data starting from that point till the end.

这篇关于用Java在文件中写入第xth行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆