AyaZoghby
AyaZoghby

Reputation: 341

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?

Upvotes: 1

Views: 20252

Answers (2)

Rahul
Rahul

Reputation: 16335

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

Upvotes: 3

droidchef
droidchef

Reputation: 2307

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.

Upvotes: 0

Related Questions