简体   繁体   English

如何在Java中读取和拆分txt文件的内容?

[英]How to read and split the contents of txt file in Java?

I want to read the whole text of a file and then split it according to specific delimiters. 我想阅读文件的全文,然后根据特定的分隔符将其拆分。 How could I do so in Java? 我怎么能在Java中这样做?

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());
  }

Read the contents. 阅读内容。 Choose a delimiter up to which you want to check each line/word or phrase for the splitting. 选择要为其检查每个行/单词或短语以进行拆分的分隔符。 Have a switch case setup. 有一个开关盒设置。 Whatever content you find based on the switch case you can perform actions. 无论您根据开关案例找到什么内容,都可以执行操作。 Say you can write in different text files from different cases. 假设您可以编写不同案例的不同文本文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM