读取txt文件的行后删除单词
我有此代码,用于从文件中读取行并将其插入帖子中:
try {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"C:\\in_progress\\test.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
Thread.sleep(100);
Optional<ProcessedWords> isFound = processedWordsService.findByKeyword(line);
if(!isFound.isPresent()){
ProcessedWords obj = ProcessedWords.builder()
.keyword(line)
.createdAt(LocalDateTime.now())
.build();
processedWordsService.save(obj);
}
// read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
如何在将行插入SQL数据库后从文件中删除一行?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当前代码的问题:
findbykeyword()
调用,准备数据并将其送出来存储在数据库中。几乎无法对其进行彻底的测试,并且很难维持。异常
类型 - 您的代码只能捕获thous例外,这或多或少是预期的,并且对于如何处理它们有一个明确的方案。但是不要捕获所有例外。从字面意义上讲,不可能从文件中删除一行。您可以覆盖文件的内容或用另一个文件替换。
我的建议是将数据归档,对其进行处理,然后写入应将其保留到同一文件中的行( ie替代文件内容)。
您可以争辩说该文件很大,将其转储到内存中会导致
OutofmemoryError
。而且您想从文件中读取一行,以某种方式对其进行处理,然后将处理的数据存储到数据库中,然后将行写入文件中...以便所有操作都是按行完成的因此,所有代码都以一种方法塞满了。我希望事实并非如此,因为否则它是一个清晰的xy-problem
。首先,文件系统不是存储数据的可靠均值,并且不是很快。如果文件庞大,那么阅读和写作将花费大量时间,并且它只是为了使用细小的信息而完成此方法,那么此方法是错误的 - 该信息应以不同的方式存储和结构化(即考虑将其放入DB),以便可以检索所需的数据,并且删除不再需要的条目没有问题。
但是,如果文件是精益的,并且不包含关键数据。然后完全可以,我将继续假设是这种情况。
总体方法是生成映射
map&lt;字符串,可选&lt; processedwords&gt;&gt;
基于文件内容,处理非空置选项并准备一条列表以覆盖先前的文件内容。下面的代码基于NiO2文件系统API。
从文件中处理线路,返回
files.lines()
:保存
findbyKeykeyword()
>的单词返回一个空的可选:生成一个线列表要保留:
使用
files.write.write.write.write.write ()
。 注意: 由于varargsopenoption
没有提供任何参数,此调用将被视为create> create> create> create
,truncate_existing
和写入
选项。The issues with the current code:
findByKeyword()
call, prepares the data and hands it out to store in the database. It's hardly can be thoroughly tested, and it's very difficult to maintain.Exception
type - your code should only catch thous exceptions, which are more or less expected and for which there's a clear scenario on how to handle them. But don't catch all the exceptions.It is not possible to remove a line from a file in the literal sense. You can override the contents of the file or replace it with another file.
My advice would be to file data in memory, process it, and then write the lines which should be retained into the same file (i.e. override the file contents).
You can argue that the file is huge and dumping it into memory would result in an
OutOfMemoryError
. And you want to read a line from a file, process it somehow, then store the processed data into the database and then write the line into a file... So that everything is done line by line, all actions in one go for a single line, and as a consequence all the code is crammed in one method. I hope that's not the case because otherwise it's a clearXY-problem
.Firstly, File System isn't a reliable mean of storing data, and it's not very fast. If the file is massive, then reading and writing it will a take a considerable amount of time, and it's done just it in order to use a tinny bit of information then this approach is wrong - this information should be stored and structured differently (i.e. consider placing into a DB) so that it would be possible to retrieve the required data, and there would be no problem with removing entries that are no longer needed.
But if the file is lean, and it doesn't contain critical data. Then it's totally fine, I will proceed assuming that it's the case.
The overall approach is to generate a map
Map<String, Optional<ProcessedWords>>
based on the file contents, process the non-empty optionals and prepare a list of lines to override the previous file content.The code below is based on the NIO2 file system API.
Processing the stream of lines from a file returned
Files.lines()
:Saving the words for which
findByKeyword()
returned an empty optional:Generating a list of lines to retain:
Overriding the file contents using
Files.write()
. Note: since varargsOpenOption
isn't provided with any arguments, this call would be treated as if theCREATE
,TRUNCATE_EXISTING
, andWRITE
options are present.供参考
阅读文件。
1:决定是删除线路还是保留线路的条件。
2:写那些不想删除到临时文件中的行。
3:删除原始文件。
4:将临时文件重命名为原始文件名。
For Reference
Read the file.
1: The condition to decide whether to delete the line or to retain it.
2: Write those line which you don't want to delete into the temporary file.
3: Delete the original file.
4: Rename the temporary file to original file name.
基本思想与@shiva Rahul在答案中所说的相同。
但是,另一种方法可以是,将要删除的所有行号存储在
list
中。拥有要删除的所有必需的行号后,您可以使用Linenumberreader
检查并复制主文件。通常,我在批处理插入中使用了这种技术,我不确定有多少行可能具有特定的文件加,然后删除行必须进行很多处理。
它可能不适合您的案件,只需在此处发布建议,如果有人碰到此线程。
要使用此功能,您要做的就是收集所有必需的行号。
inputfilepath
是源文件的路径,outputdirectory
是我想要在处理后存储文件的地方。The basic idea is the same as what @Shiva Rahul said in his answer.
However another approach can be , store all the line numbers you want to delete in a
list
. After you have all the required line numbers that you want to delete you can useLineNumberReader
to check and duplicate your main file.Mostly I have used this technique in batch-insert where I was unsure how many lines may have a particular file plus before removal of lines had to do lot of processing.
It may not be suitable for your case ,just posting the suggestion here if any one bumps to this thread.
To use this function all you have to do is gather all the required line numbers.
inputFilePath
is the path of the source file andoutputDirectory
is where I want store the file after processing.