• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 402
  • Last Modified:

Using java.util.Scanner to Delimit a File On Asterisks

I'm having trouble using the java.util.Scanner class to delimit a file.  What I am trying to do is break up a file which is separated by the * (asterisk) character.

The file is something like this:

Asterisk*Delimited*File

Becomes:

Asterisk
Delimited
File

Here's what I have tried so far:

labelFile = new Scanner(new File("Text.txt"));
labelFile.useDelimiter("*");   //Also tried "\u002A"
                  
while(labelFile.hasNext())
{
      System.out.println(labelFile.next());
}

I can't seem to get any character-based patterns to work.  Anyone see what I am doing wrong?  Thanks for any help.

--Charly
0
dleehanson
Asked:
dleehanson
  • 2
  • 2
1 Solution
 
UrosVidojevicCommented:
Hi dleehanson,

The problem is isolated in this line: abelFile.useDelimiter("*");

useDelimiter() method takes as an argument an regular expression. It is interesting that asterisk character '*' is a special character in regular expressions, so it can't be used alone. Instead of that you need to put it inside [] brackets.

So, you need to write:

labelFile.useDelimiter("[*]");

instead of:

labelFile.useDelimiter("*");

Hope this helps,
Uros.
0
 
objectsCommented:
try escaping the *

labelFile.useDelimiter("\\*");
0
 
dleehansonAuthor Commented:
Uros,

Worked like a charm.  Thank you.  Do you know of any good resources/tutorials for delimiting files or making patterns?  This seems like it would be a good topic to have a better understanding of.

--Charly
0
 
UrosVidojevicCommented:
Regular Expressions are probably the best solution for this kind of problems. [searching&extracting patterns, delimiting text,...]

http://java.sun.com/docs/books/tutorial/essential/regex/
http://www.regular-expressions.info/reference.html

Useful classes:
StringTokenizer http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html
Pattern: http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html

String class has also few methods dealing with regular expressions.
0
 
dleehansonAuthor Commented:
Thanks for the follow-up.  I'll have to take some time and dig into those links.

--Charly
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now