Reading a line from a text file Java - java

I am trying to read a line from a file using BufferedReader and Scanner. I can create both of those no problem. What I am looking to do is read one line, count the number of commas in that line, and then go back and grab each individual item. So if the file looked like this:
item1,item2,item3,etc.
item4,item5,item6,etc.
The program would return that there are four commas, and then go back and get one item at a time. It would repeat for the next line. Returning the number of commas is crucial for my program, otherwise, I would just use the Scanner.useDelimiter() method. I also don't know how to return to the beginning of the line to grab each item.

Why not just split the String. The split method accepts a delimiter (regex) as an argument and breaks the String into a String[]. This will eliminate the need to return to the beginning.
String value = "item1,item2,item3";
String[] tokens = value.split(",");
To get the number of commas, just use, tokens.length - 1
String.split() Documentation

Split() can be used to achieve this
eg:
String Line = "item1,item2,item3"
String[] words =Line.split(",");

If you absolutely must know the number of commas, a similar question has already been answered:
Java: How do I count the number of occurrences of a char in a String?

Related

Print all text in-between two characters

I want to print a specific part of text from a text file.
For example :
number)street)city)state)country)
I want to print from ) to ) so that any street name or country can go into the text file. What I have done is:
I have tried connecting scanner to the file and creating a while loop with .hasNextLine();
Then creating a String for the whole of the text file String line = textscanner.nextLine();
Then to print out country for example, I would create a substring System.out.print(line.substring(25));
However, this won't work if there are different street or country names in the file. How do I make it so that it will print anything from the ) to )?
You have to take advantage of Java's split() method, which accepts a specified string of text to use as separators/delimiters to words, which are often commas, like in .csv files. I'm going to skip the part about reading the file and just use this string as an example and put the words into an array:
String line = "number)street)city)state)country)";
String[] words = line.split("\\)");
Note in your case you must use double backslashes or the compiler will throw an error saying no matching parentheses.

How to split two lines in java ? while i try to split by /n , the string is printing with garbage value :(

While I tried splite a line by below code. getting the result some garbage. while i printed the value of selectedproduct.get(j).getText() I'm getting the below string
Civil War A Nation Divided
Playstation2 Software
I just required the upper one.
System.out.println(selectedproduct.get(j).getText().split("\\n"));
String.split() returns an array of values between each occurrence of the delimiter. The reason you're getting "garbage" values is because arrays use the default implementation of toString(). To print the full array, you can use Arrays.toString():
System.out.println(Arrays.toString(selectedproduct.get(j).getText().split("\\n")));
If you only want the first line, just print the first element of the returned array:
System.out.println(selectedproduct.get(j).getText().split("\\n")[0]);
The .split() would create an array of strings so to get teh first part of splitted array use the index as you print.
System.out.println(selectedproduct.get(j).getText().split("\\n")[0]); //index of upper line for you
Also in some cases you might want to use \r\n for platform specific carriage return -
System.out.println(selectedproduct.get(j).getText().split("\\r\\n")[0]);

Reading a txt file, and putting each word into an array, without punctuation or numbers

I am wondering how I would read a txt file with Java, and put each word from the txt file into a different bucket in an array, but without punctuation or numbers that are in the file. I'm only interested in storing the words.
So if the text file contained: "25 chickens crossed the road." the program should create an array like {"chickens", "crossed", "the", "road"}
I would like to do this on a fairly large text file. Will I run into any run time issues?
If you could explain it to me like I'm a complete noob, that would be great.
I appreciate it.
Do a .replaceAll(regex, "") which will replace all matching characters with the contents of the second parameter (an empty string in this case). Matching is done with a regular expression.
Second step is to use .split(regex) on your returned string from replaceAll, and split the string on space ( .split(" ") ). This will return an array with all the words separate.
An easy way to write regular expressions is to use http://www.regexr.com
Example code: (not tested)
String oldText = "25 chickens crossed the road.";
String newText = oldText.replaceAll("\!|\.|\?|\d/g","");
String[] strArray = newText.split(" ","");

How to remove first string and comma from a text file

!
I have a text, the content looks like [1,'I am java, and I am happy, I am.....'], I want to remove the first integer and the comma. When I was run the code above, but the result start with last comma: I am......
If you only want to remove commas from a String, you can use String.replaceAll(",",""); If you want to replace them by spaces, use String.replaceAll(","," "):
while ((line = br.readLine()) != null) {
contents.append(line.replaceAll(","," ");
}
Also in your code you seem to split the input, but don't use the result of this operation.
You need to use the indexOfReturns the index within this string of the first occurrence of the specified character, starting the search at the specified index..
lastIndexOf Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
System.out.print(s.substring(s.indexOf(",")+1));
Use this following code as:
System.out.println(line.substring(2));
sub string takes the beginning index as a parameter and splits the string from that index to till the end.
Note that you are using lastIndexOf(). Use indexOf() to get the first index as shown below.
System.out.println(test.substring(line.indexOf(',')+1));
I'm taking your String literially, but you could use String#replaceFirst, for example...
String text = "[1,'I am java, and I am happy, I am.....']";
text = text.replaceFirst("\\[\\d,", "[");
System.out.println(text);
Which outputs...
['I am java, and I am happy, I am.....']
If you want to update the file, you are either going to have to read all the lines into some kind of List (modifying them as you please) and once finished, write the List back to the file (after you've closed it after reading it).
Alternatively, you could write each updated line to a second file, once you're finished, close both files, delete the first and rename the second back in it's place...
Try This code:
String[] s=line.splite(",");
String m="";
for(int i=1;i<s.length;i++)
{
String m=m+s[i];
}
br.append(m);
String input = "[1,'I am java, and I am happy, I am.....']";
//Getting String after first comma
String output = StringUtils.substringAfter(input, ",");
System.out.println("Output:"+output);
//replacing commas;
System.out.println("Final o/p:"+StringUtils.replace(output, ",",""));
You can use methods in StringUtils Class for string manipulations. For using StringUtils methods, you need to import apache-commons-lang.jar file. Using this API you can manipulate many String related methods. For more details, you can see the link
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html

Suggested ways of reading a text file with inconsistent formatting

I'm trying to read a text file of numbers as a double array and after various methods (usually resulting in an input format exception) I have come to the conclusion that the text file I am trying to read is inconsistent with it's delimiting.
The majority of the text format is in the form "0.000,0.000" so I have been using a Scanner and the useDelimiter(",") to read in each value.
It turns out though (this is a big file of numbers) that some of the formatting is in the form "0.000 0.000" (at the end of a line I presume) which of course produces an input format exception.
This is an open question really, I'm a pretty basic Java programmer so I would just like to see if there are any suggestions/ways of performing this. Is Scanner the correct class to go on this?
Thank you for your time!
Read file as text line-by-line. Then split line into parts:
String[] parts = line.split("[ ,]");
Now iterate over the parts and call Double.parseDouble() for each part.
Scanner allows any Java Regex Pattern to function as a delimiter. You should be able to use any number of delimiters by doing the following:
scanner.setDelimiter("[,\\s]"); // Will match commas and whitespace
I'd like to comment this in instead of making it a separate answer, but my reputation is too low. Apologies, Alex.
You mentioned having two different delimited characters used in different instances, not a combination of the two as a single delimiter.
You can use the vertical bar as logical OR in a regular expression.
scanner.setDelimiter("[,|\\s]"); //Will match commas or whitespace as appropriate
line by line:
String[] parts = line.split("[,|\\s]");

Categories