用Java编写一个文本文件的中间部分 [英] Writing to the middle of a text file in Java

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

问题描述

在Java中写入文本文件的最佳方式是什么?



我知道,没有什么能够读取整个文件到内存然后写回来。但解析实际上是我的弱技能之一,与文件I / O相关的众多类是令人困惑的(在File,FileWriter,FileOutputStream,BufferedWriter ... AHHHHH !!之间选择)

假设我有这样一个文本文件:


快速的棕色狐狸跳过了懒狗。那只懒狗笑着傻傻的跳跃狐狸
。狗的名字叫Puff。


假设我想在dog前添加cute这个形容词,导致这个:


快速的棕色狐狸跳过懒惰的可爱的狗。那只懒洋洋的可爱狗笑着傻傻的跳狐狸。 可爱狗的名字叫Puff。

我想我需要一个支持插入的数据结构,所以char数组可能不起作用。

解决方案

由于您正在处理文本文件,我认为最简单的方法是使用 a>。

您可以使用 hasNextLine() nextLine() ,将每行一行读入一个字符串变量,执行转换,并将结果打印出来(比如说 PrintStream )。

为此,您需要先将结果写入临时文件,然后删除输入文件并重命名临时文件给它t他和输入文件一样。

What's the best way to write to the middle of a text file in Java?

I know that there's no getting around reading the entire file to memory and then writing it back. But parsing is really one of my weak skills and the multitude of classes related to file I/O is confusing (choosing between File, FileWriter, FileOutputStream, BufferedWriter... AHHHHH!!)

Let's say I have a text file like this:

The quick brown fox jumped over the lazy dog. The lazy dog laughed at the silly jumping fox. The dog's name was Puff.

Let's say I want to add the adjective "cute" in front of "dog", resulting in this:

The quick brown fox jumped over the lazy cute dog. The lazy cute dog laughed at the silly jumping fox. The cute dog's name was Puff.

I guess I would need a data structure that supports insertion, so a char array probably wouldn't work.

解决方案

Since you're dealing with a text file, I think the easiest way is to use Scanner.

You could use hasNextLine() and nextLine() to read the lines one at a time into a String variable, do the transformation, and print out the result (say, into a PrintStream).

For this to work, you'll need to first write out the result into a temporary file, then delete the input file and rename the temp file to give it the same name as the input file.

这篇关于用Java编写一个文本文件的中间部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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