java - 读取文件上传中的多行

标签 java file upload

谁能告诉我如何读取多行并存储它们的值。

例如:file.txt

Probable Cause: The network operator has issued an alter attribute command for
the specified LCONF assign. The old value and the new value are show
Action Taken : The assign value is changed from the old value to the new
value. Receipt of this message does not guarantee that the new attribute
value was accepted by clients who use it. Additional messages may be.

Probable Cause: The network operator has issued an info attribute command for
the specified LCONF assign. The default value being used is displaye
Action Taken : None. Informational use only.

在上面的文件中,可能的原因和采取的操作是数据库表的列。在“可能原因”之后:这些是要存储在数据库表中的“可能原因”列的值,所采取的操作也是如此。

那么我如何读取多行并存储它们的值?我必须读取可能原因的值,直到该行出现“已采取的操作”。我使用 BufferedReader 和 readLine() 方法一次读取一行。那么谁能告诉我如何直接从可能的原因读取采取的行动,无论它们之间有多少行。

最佳答案

最简单的方法可能就是保留 List<String>对于每个值,循环某事如下:

private static final String ACTION_TAKEN_PREFIX = "Action Taken ";

...

String line;
while ((line = reader.readLine()) != null)
{
    if (line.startsWith(ACTION_TAKEN_PREFIX))
    {
        actions.add(line.substring(ACTION_TAKEN_PREFIX))
        // Keep reading the rest of the actions
        break;
    }
    causes.add(line);
}
// Now handle the fact that either we've reached the end of the file, or we're
// reading the actions

获得“可能原因”/“采取的操作”对后,将字符串列表转换回单个字符串,例如用“\n”连接,然后插入数据库。 (Guava 中的 Joiner 类将使这变得更容易。)

棘手的一点是处理异常:

  • 如果不从可能的原因开始会发生什么?
  • 如果一个可能的原因之后是另一个可能的原因,或者一组操作之后是另一组操作,会发生什么?
  • 如果您在阅读了可能的原因但没有操作列表后到达文件末尾,会发生什么情况?

我现在没有时间写出完整的解决方案,但希望以上内容能帮助您继续前进。

关于java - 读取文件上传中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9782341/

相关文章:

java - 如何在java中将字符串设置为日期数据类型

java - 打开一个二进制文件并打印该文件中的所有 ASCII 字符

java - 尝试在 java 中上传图像时出现 NoSuchFileException

javascript - 图像上传部分中的跨浏览器图像预览在 ie8 中不起作用

java - 按条件从数组列表中选择 3 个元素

java - spring mvc注解@Inject不起作用

java - 如何绕过 JDBCTemplate org.springframework.dao.DuplicateKeyException

java - 为什么 setLastModified(time) 不适用于此文件?

java - 在连接PC的移动设备上读写数据

android - 在Android中上传大文件而不会出现内存不足错误