Alex
Alex

Reputation: 125

How to read a string of characters from a text file until a certain character, print them in the console, then continue?

i have a question. I have a text file with some names and numbers arranged like this :

Cheese;10;12

Borat;99;55

I want to read the chars and integers from the file until the ";" symbol, println them, then continue, read the next one, println etc. Like this :

Cheese -> println , 10-> println, 99 -> println , and on to the next line and continue.

I tried using :

BufferedReader flux_in = new BufferedReader (
                         new InputStreamReader (
                         new FileInputStream ("D:\\test.txt")));

while ((line = flux_in.readLine())!=null && 
line.contains(terminator)==true)
{
    text = line;
    System.out.println(String.valueOf(text));   
}

But it reads the entire line, doesn`t stop at the ";" symbol. Setting the 'contains' condition to false does not read the line at all.

EDIT : Partially solved, i managed to write this code :

    StringBuilder sb = new StringBuilder();
//  while ((line = flux_in.readLine())!=null)

        int c;
        String terminator_char = ";";
        while((c = flux_in.read()) != -1) {
        {
         char character = (char) c;
             if (String.valueOf(character).contains(terminator_char)==false)
              {
    //       System.out.println(String.valueOf(character) + " : Char");
                 sb.append(character); 
              }
              else 
              {
                  continue;
              }
            }
        }
        System.out.println(String.valueOf(sb) );

Which returns a new string formed out of the characters from the read one, but without the ";". Still need a way to make it stop on the first ";", println the string and continue.

Upvotes: 0

Views: 5537

Answers (2)

Alex
Alex

Reputation: 125

This simple code does the trick, thanks to Stefan Vasilica for the ideea :

Scanner scan = new Scanner(new File("D:\\testfile.txt"));
    // Printing the delimiter used
    scan.useDelimiter(";");
    System.out.println("Delimiter:" + scan.delimiter());
    // Printing the tokenized Strings
    while (scan.hasNext()) {
        System.out.println(scan.next());
    }
    // closing the scanner stream
    scan.close();

Upvotes: 1

Stefan Vasilica
Stefan Vasilica

Reputation: 16

  1. Read the characters from file 1 by 1
  2. Delete the 'contains' condition
  3. Use a stringBuilder() to build yourself the strings 1 by 1
  4. Each stringBuilder stops when facing a ';' (say you use an if clause)

I didn't test it because I'm on my phone. Hope this helps

Upvotes: 0

Related Questions