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
Related
I'm coding a program that takes in lines from an input text file.
It is supposed to be a set of strings on a single line separated by the newline character. So, my input file looks like this:
0110\n011\n0111\n100001
However, when I go to print out each line, it comes out as one entire string, including the new line characters - '0110\n011\n0111\n100001'
This is my code - it works fine for Scanner when it's a static string, but not when it's from a file.
File input = new File(input.txt);
Scanner scanner = new Scanner(input);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
When I change the scanner to read a String s, like Scanner scanner = new Scanner(s) for a String s = "0110\n011\n0111\n100001", it works correctly and prints out 4 lines, which means it recognizes the \n character, as such:
String s = "0110\n011\n0111\n100001";
Scanner scanner = new Scanner(s);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
The only thing that's holding me back is that we have to separate the input file strings by \n. That's a requirement for our project.
Any idea why this happens? Is my text file wrong, is there a way to split it up by \n? Does Scanner read lines in files differently than just static strings? Should I just switch to BufferedReader? I can't wrap my head around this. I read through some forums and manuals and I couldn't find anything on it. If I can do anything, or provide anything else, please let me know.
\n is a new line symbol, which when in a string is interpreted as such, but in your file you should just hit the enter key, which will make a new line for you and the scanner will read everything right.
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.
Here is the data that I am extracting from a txt:
1|Fred|Fish|fredfish#gamer.net|Ithroeann|19770322
2|Laurie|Nash|laurieeenash#gmail.com|Mazzzap|19820828
3|Conrad|Washington|fredfish#gamer.net|Crayonbreath|19720712
Here is the code for scanner to read the content from the txt:
File file = new File("players.txt");
Scanner s = new Scanner(file);
while (s.hasNextLine()) {
String line = s.nextLine();
s.close();
I was wondering is there any way to merge each individual line from the scanner into a single string output.
The string output will then be used by my other method to split it into different player objects.
Thank you in advance.
You can create an object of StringBuilder. As you fetch a line from the file you can use its append() method. Once you read and append all the lines you can get the String object by invoking toString() on the object of StringBuilder.
Also note that you can use + on Simple String objects but as objects of class String are immutable hence doing so will result in lot of String objects which will be a performance kill. Hence StringBuilder is preferably better choice.
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.
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|:]+");