【问题标题】:How to read and split the contents of txt file in Java?如何在Java中读取和拆分txt文件的内容?
【发布时间】:2012-12-08 07:00:29
【问题描述】:

我想读取文件的整个文本,然后根据特定的分隔符将其拆分。 我怎么能在 Java 中这样做?

【问题讨论】:

  • 分割文件应该有一个条件。要么你想根据 size[bytes] / demeter 分割。请完成问题

标签: java file text split


【解决方案1】:
try{
  // Open the file
  FileInputStream fstream = new FileInputStream("textfile.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
  // split the line on your splitter(s)
     String[] splitted = strLine.split("-"); // here - is used as the delimiter
  }
  //Close the input stream
  in.close();
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }

【讨论】:

  • 非常感谢您的回复。
  • 但是为什么我要逐行阅读文本呢?这可能会导致我的结果出现错误,因为它也会在额外的位置吐出,这是行尾!!
【解决方案2】:

阅读内容。选择要检查每个行/单词或短语以进行拆分的分隔符。有一个开关盒设置。无论您根据 switch case 找到什么内容,都可以执行操作。假设您可以在不同的情况下写入不同的文本文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 2015-08-15
    相关资源
    最近更新 更多