How do I change the delimiter from a text file? - java

Let's say I got a textfile.txt that I want to read from. This is the text in the file:
23:years:old
15:years:young
Using the useDelimiter method, how can I tell my program that : and newlines are delimiters? Putting the text in one line and using useDelimter(":"); works. The problem is when I got several lines of text.
Scanner input = new Scanner(new File("textfile.txt));
input.useDelimiter(:);
while(data.hasNextLine()) {
int age = input.nextInt();
String something = input.next();
String somethingelse = input.next();
}
Using this code I will get an inputMisMatch error.

Try
scanner.useDelimiter("[:]+");
The complete code is
Scanner scanner = new Scanner(new File("C:/temp/text.txt"));
scanner.useDelimiter("[:]+");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
The output is
23
years
old
15
years
young

Use this code
Scanner input;
String tokenizer[];
try {
input = new Scanner(new File("D:\\textfile.txt"));
input.useDelimiter("\\n");
while(input.hasNextLine()) {
tokenizer = input.next().split(":");
System.out.println(tokenizer[0]+" |"+tokenizer[1]+" | "+tokenizer[2]);
}
}catch(Exception e){}
It will give you output like
23 |years | old
15 |years | young

You have two ways to do this:
Concatenate the string to make it one line.
delimit "newline" first, then delimit ":" each return string token.

If all you want is to get everything split up all at once then I guess you can use
useDelimiter(":\\n")
That should split on both : and newspace but it is not the most efficient way of processing data, especially if each line of text is set out in the same format and represents a complete entry. If that is the case then my suggestion would be to only split on a new line to begin with, like this;
s.useDelimiter("\\n");
while(s.hasNext()){
String[] result = s.next.split(":");
//do whatever you need to with the data and store it somewhere
}
This will allow you to process the data line by line and will also split it at the required places. However if you do plan on going through line by line I recommend you look at BufferedReader as it has a readLine() function that makes things a lot easier.

As long as all the lines have all three fields you can just use input.useDelimiter(":\n");

you probably wants to create a delimiter pattern which includes both ':' and newline
I didn't test it, but [\s|:]+ is a regular expression that matches one or more whitespace characters, and also ':'.
Try put:
input.useDelimiter("[\\s|:]+");

Related

Not able to assign a text for a string in array using split method

I have a question about my split function inside the file reading function.
Here is my code. I tried to use split to put these text in to array. But the problem is I have this error. java.lang.NumberFormatException: For input string: "Sug" at java.base/java.lang.NumberFormatException.forInputString
public static SLL<train> readFile() {
SLL<train> list = new SLL();
try {
FileReader fr = new FileReader("Train.dat");
BufferedReader br = new BufferedReader(fr);
String line = "";
while (true) {
line = br.readLine();
if (line == null) {
break;
}
String[] text = line.split(" | ");
String tcode = text[0];
String train_name = text[1];
int seat = Integer.parseInt(text[2]);
int booked = Integer.parseInt(text[3]);
double depart_time = Double.parseDouble(text[4]);
String depart_place = text[5];
train t = new train(tcode, train_name, seat, booked, depart_time, depart_place);
list.addLast(t);
}
br.close();
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
This is my text file:
"SUG" should be added into train name because I declared train_name as a string.I think this error only appears when declaring the wrong data type, "12" should be added into seat, "3" should be added into booked, and so on. Can you guys explained to me what happened to "SUG". Thanks a lot :(
Note that String.split(regex) uses a regex to find the split location, i.e. it splits before and after any match produced by the regular expression.
Furthermore, in regex the pipe (|) has the special meaning "or" so your code right now reads as "split on a space or a space". Since this splits on spaces only, splitting "B03 | Sug | 12 ..." will result in the array ["B03","|","Sug","|","12",...] and hence text[2] yields "Sug".
Instead you need to escape the pipe by either using line.split(" \\| ") or line.split(Pattern.quote(" | ")) to make it "split on a sequence of space, pipe, space". That would then result in ["B03","Sug","12",...].
However, you also might need to surround Integer.parseInt() etc. with a try-catch block or do some preliminary checks on the string because you might run into a malformed file.
In addition to what #Thomas has said, it would be a whole lot easier to use a Scanner
sc.useDelimiter("\\s*\\|\\s*");
while (sc.hasNext()) {
Train t = new Train(sc.next(), sc.next(), sc.nextInt(), sc.nextInt(), sc.nextDouble(), sc.next());
}
Naming is important in Java for readability and maintenance
Note class names begin upper case in Java. There's no place for underscores except for as separators for blocks of capitals in the name of a constant.

Why am I getting an InputMismatchException with?

I created a Scanner in java to read through a file of data regarding a city. The file is formatted as such:
Abbotsford,2310,2
Adams,1967,1
Algoma,3167,2
When reading through the file, I get an InputMismatchException when scanning the last item on each line (This item needs to be an int).
public void fileScanner(File toScan) throws FileNotFoundException {
Scanner sc = new Scanner(toScan);
sc.useDelimiter(",");
System.out.println(sc.next());
System.out.println(sc.nextInt());
System.out.println(sc.nextInt());
Any ideas as to why? I'd imagine it has something to do with my use of the "," delimiter.
You are using only one delimiter i.e. , but your file contains \r or \n so try to use multiple delimiters. Also, use a loop to read the entire file:-
Scanner sc = new Scanner(toScan);
sc.useDelimiter(",|\\r\\n");
while (sc.hasNext()) {
System.out.println(sc.next());
System.out.println(sc.nextInt());
System.out.println(sc.nextInt());
}
OUTPUT:-
Abbotsford
2310
2
Adams
1967
1
Algoma
3167
2
The delimiter you're using is comma(,)
The system looks for the next comma, which comes only after Adams. So the input for the system looks like 2 Adams which is obviously not an Int , rather a String and hence the inputMisMatch.
If you make your data something like below, your code would work great.
Abbotsford,2310,2,
Adams,1967,1,
Algoma,3167,2,
Also I see there's no loop to read all the data. Your code will read just the first line.

How do I separate a string like this line by line?

I have a string that I want to read line by line:
"8688642986379252 Michael_Thompson 816 2500.0
8904000405634912 Barbara_Martin
8610835007621519 Charles_Jackson 1019 52800.0"
It goes on on and on in that format.
I tried separating it using for loops, charAt() and reducing the size of the string using substring() but I failed miserably.
I'm sure it's something simple but I just can't get it. Any ideas?
I would suggest using str.split("\n"). It will produce an array of strings, one index for each line. This is assuming you can read the whole thing into a string. If the input is large, this won't work.
Use Scanner to read line by line using nextLine. Then, split every String by blank space" ":
Scanner scanner = new Scanner(stringWithBreaklines);
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] content = line.split(" ");
//do what you want/need with content
}
If the String is inside a file, then read the file directly using Scanner:
Scanner scanner = new Scanner(new File("file.txt"));
//same code as above...
Use the java.util.Scanner class to read tokens one by one.
http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

Java - Reading in value from text

OK so I have read plenty of examples on here dealing with reading in lines from a text file and splitting them up but im not quite sure I understand how to do it in my situation. I have a file that is basically separated into three columns as follows:
START 5000
FIND A
PLUS B
SAVE C
STOP
A, INT 69
B, INT -420
C, CRAZY 008484342
What I am trying to do is read in this .txt file containing the above information. I figured reading in the file line by line would be best, then splitting it into the correct columns. The problem that I am having is the fact that the 1st column is not always here. It is an optional one. If they were all filled in, im almost positive I could just use use something like
String[] array1 = myLine.split(",");
Another idea I had was to split the line based on ,'s then split the line again based on " " but im not exactly sure how to do this. Maybe somthing like
String[] array1 = myLine.split(",");
String[] array2 = array1[1].split(" ");
Also, is there any way to just read in the file and store each row into like (String, String String) then just check for ints vs strings? Maybe in a try catch? or like:
Scanner input = new Scanner(File);
while(input.hasNext()){
String str = input.next();
try{
b = Integer.parseInt(str);
}
I am not sure if this is as hard as a task as im making it but maybe so... Any help with this topic would be appreciated.
After looking over some more code, I have the following to start:
public static void main(String[] args) {
String file ="TEST.txt";
try{
FileReader input = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(input);
String line;
while ((line = bufferReader.readLine()) != null) {
// Is this where I would attempt to split the lines?
System.out.println(line);
}
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:" + e.getMessage());
}
}
}
So with this, I am successfully reading in the file and displaying the information back to the output console. Now for separating the lines... Ill be posting my work as I go, any help and or suggestions would be appreciated! Also thank you to those who have already commented with helping to split the stings, ill be attempting this now!
You can combine both expressions and only checked the array's length. e.g.:
String[] array = line.trim().split("[, ]+");
switch(array.length) {
case 2:
// do something
break;
case 3:
// do something
break;
default:
// something wrong
break;
}
The trim() in the line is for avoid empty string in the first element array.
Use split(" +") which will split on any numbers of spaces. This works because split handles regex. If you want to split on any type of whitespace you can also use split("\\s+). After you get the array check if it has 2 or 3 elements and handle it accordingly.
Well ... I don't have the time yet for a long answer. But I'd recommend you to read a little bit about regular expressions (RegEx) and how it is used in java ... I am sure this will help you with this problem and a huge amount of future problems like this ...
Try this: http://www.vogella.com/articles/JavaRegularExpressions/article.html ... of this http://docs.oracle.com/javase/tutorial/essential/regex/ ... if the first one does not help ;)

Java: Error with reading in file with delimiter

I have a file with multiple fields that i need to store individually into an array.
Steve;stiffy;123;88
Sam;sammy;456;55
But when i try storing them i keep getting error saying java.util.NoSuchElementException
Here is my code for storing the data
void loadCustomer(){
try {
Scanner sc = new Scanner(new File("CustomerInfo.txt"));
sc.useDelimiter(";");
while (sc.hasNext())
{
cusName.add(sc.next());
cusUser.add(sc.next());
cusPass.add(sc.next());
cusCCNum.add(sc.next());
}
}
I could get it to work by changing
cusCCNum.add(sc.next());
to
cusCCNum.add(sc.nextLine());
but it will ignore the delimiter and when i print out cusCCNum.get(1), it will display
;88
instead of
88
Where did i go wrong?
There is no delimiter between 88 and Sam..
scanner.useDelimiter(";|\n");
Use String tokenizer instead of delimiter.
Get input as a string and parse it by ; character as token.
Learn, how to use stringtokenizer here
You are causing the exception while you are calling the 4 next elements for each one check if there is 1 next element, this would do the following:
while (RecentElement is not the last one)
{
Read (RecentElement + 1)
Read (RecentElement + 2)
Read (RecentElement + 3)
Read (RecentElement + 4)
}
And somewhen you get the exception of the next() method because you access an element that is just not there:
Throws: NoSuchElementException - if no more tokens are available
You should use the new line as a delimiter and for each new line parse the data from the record, for example using the split function:
sc.useDelimiter("\n");
while (sc.hasNext())
{
for(String g: sc.next().split(";"))
System.out.println(g);
}
Looks like you need to read each line, token it using delimeter and set values to array.
I could do it via StringTokenizer.
while (sc.hasNextLine()) {
StringTokenizer st = new StringTokenizer(sc.nextLine(),";");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
}
I am surprised and need to read more on Scanner api to see why its not working with scanner.

Categories