This question already has answers here:
How do I use a delimiter with Scanner.useDelimiter in Java?
(3 answers)
Closed 4 years ago.
This is what I have been working so far for reading a text file,
Scanner file = new Scanner(new File("sample.txt")).useDelimiter(".");
ArrayList<String> arr = new ArrayList<>();
while (file.hasNextLine()) {
strList.add(file.nextLine());
}
file.close();
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
}
and my text file looks like this,
I love you. You
love me. He loves
her. She loves him.
I want a result of the code like,
I love you
You love me
He loves her
She loves him
But the result is same as the text file itself. Isn't that "useDelimiter(".")" suppose to separate the text file with period(".")?
I've also tried to use hasNext() and next() instead of hasNextLine() and nextLine(), but it prints out empty 30ish new lines.
That's because useDelimiter accepts a pattern. The dot . is a special character used for regular expressions meaning 'any character'. Simply escape the period with a backslash and it will work:
Scanner file = new Scanner(new File("sample.txt")).useDelimiter("\\.");
EDIT
The problem is, you're using hasNextLine() and nextLine() which won't work properly with your new . delimiter. Here's a working example that gets you the results you want:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
final static String path = Test.class.getResource("sample.txt").getPath();
public static void main(String[] args) throws IOException {
Scanner file = new Scanner(new File(path)).useDelimiter("\\.");
List<String> phrases = new ArrayList<String>();
while (file.hasNext()) {
phrases.add(file.next().trim().replace("\r\n", " ")); // remove new lines
}
file.close();
for (String phrase : phrases) {
System.out.println(phrase);
}
}
}
by using hasNext() and next(), we can use our new . delimiter instead of the default new line delimiter. Since we're doing that however, we've still go the new lines scattered throughout your paragraph which is why we need to remove new lines which is the purpose of file.next().trim().replace("\r\n", " ") to clean up the trailing whitespace and remove new line breaks.
Input:
I love you. You
love me. He loves
her. She loves him.
Output:
I love you
You love me
He loves her
She loves him
Related
This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(16 answers)
Closed 1 year ago.
I am trying to split a .txt file into an array so I can access individual elements from it. However I get the following error, Index 1 out of bounds for length 1 at babySort.main(babySort.java:21).
I am unsure where I am going wrong because I used the same code on a test string earlier and it splits into the appropriate amount of elements.
I suspect it has something to do with the while loop, but I can't seem to wrap my mind around it, any help would be appreciated.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class babySort {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("src/babynames.txt");
Scanner in = new Scanner(inputFile);
String test = "Why wont this work?";
String[] test2 = test.split("\\s+");
System.out.println(test2[2]);
while (in.hasNext()) {
String input = in.next();
String[] inputSplit = input.split("\\s+");
//System.out.println(Arrays.toString(inputSplit));
System.out.println(inputSplit[1]);
}
}
}
From the documentation:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
My understanding is that you want to read the input line-by-line. You can use FileReader instead of Scanner to read the file line-by-line. You can also use BufferedReader like so:
try (BufferedReader br = new BufferedReader(new FileReader(inputFile, StandardCharsets.UTF_8))) {
String input;
while ((input = br.readLine()) != null) {
// process the line
String[] inputSplit = input.split("\\s+");
//System.out.println(Arrays.toString(inputSplit));
System.out.println(inputSplit[1]);
}
}
I want to read words from a text file which looks like:
"A","ABILITY","ABLE","ABOUT","ABOVE","ABSENCE","ABSOLUTELY","ACADEMIC","ACCEPT","ACCESS","ACCIDENT","ACCOMPANY", ...
I read the words using split("\",\"") so I have them in a matrix. Unfortunately I cannot skip reading the first quotation mark, which starts my .txt file, so as a result in my console I have:
"A
ABILITY
ABLE
ABOUT
ABOVE
Do you know how can I skip the first quotation mark? I was trying both
Scanner in = new Scanner(file).useDelimiter("\"");
and parts[0].replace("\"", "");, but it doesn't work.
package list_1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class exercise {
public static void main(String[] args) throws FileNotFoundException{
File file = new File("slowa.txt");
Scanner in = new Scanner(file).useDelimiter("\""); //delimiter doesn't work!
String sentence = in.nextLine();
String[] parts = sentence.split("\",\"");
parts[0].replace("\"", ""); //it doesn't work!
for (int i=0; i<10 ; i++){
System.out.println(parts[i]);
}
}
}
Strings are immutable which means that you can't change their state. Because of that replace doesn't change string on which it was invoked, but creates new one with replaced data which you need to store somewhere (probably in reference which stored original string). So instead of
parts[0].replace("\"", "");
you need to use
parts[0] = parts[0].replace("\"", "");
Anyway setting delimiter and using nextLine doesn't make much sense because this method is looking for line separators (like \n \r \r\n), not your delimiters. If you want to make scanner use delimiter use its next() method.
You can also use different delimiter which will represent " or ",". You can create one with following regex "(,")?.
So your code could look like
Scanner in = new Scanner(file).useDelimiter("\"(,\")?");
while(in.hasNext()){
System.out.println(in.next());
}
You can use this regular expression. It works for me:
Scanner in = new Scanner(file).useDelimiter("\"(,\")?");
while(in.hasNext()){
System.out.println(in.next());
}
I do not know how to take the integer and ignore the strings from the file using scanner. This is what I have so far. I need to know how to read the file token by token. Yes, this is a homework problem. Thank you so much.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClientMergeAndSort{
public static void main(String[] args){
int length = 13;
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (!input.hasNextInt()) {
input.next();
}
int[] arraylist = new int[length];
for(int i =0; i < length; i++){
length++;
arraylist[i] = input.nextInt();
System.out.print(arraylist[i] + " ");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Take a look at the API for what you're doing.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
Specifically, Scanner.hasNextInt().
"Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."
So, your code:
while (!input.hasNextInt()) {
input.next();
}
That's going to look and see if input hasNextInt().
So if the next token - one character - is an int, it's false, and skips that loop.
If the next token isn't an int, it goes into the loop... and iterates to the next character.
That's going to either:
- find the first number in the input, and stop.
- go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going.
Write down in words what you want to do here.
Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet.
Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it.
Read the file first. Then display it as you read it, so you know it works.
Then worry about if it has numbers or not.
A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask.
Have a nice programming.
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) throws IOException {
String newStr=new String(readAllBytes(get("data.txt")));
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(newStr);
while (m.find()) {
System.out.println("- "+m.group());
}
}
}
This code fill read the file and then using the regular expression you can get only Integer values.
Note: This code works in Java 8
I Think This will work for you requirement.
Before reading the data from the file initially,try to write some content to the file by using scanner and filewriter then try to execute the below code snippet.
File file = new File(your filepath);
List<Integer> list = new ArrayList<Integer>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String str =null;
while(true) {
str = bufferedReader.readLine();
if(str!=null) {
System.out.println(str);
char[] chars = str.toCharArray();
String finalInt = "";
for(int i=0;i<chars.length;i++) {
if(Character.isDigit(chars[i])) {
finalInt=finalInt+chars[i];
}
}
list.add(Integer.parseInt(finalInt));
System.out.println(list.size());
System.out.println(list);
} else {
break;
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
The final println statement will display all the integer in your file line by line.
Thanks
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I am having an issue where when I get the program to print the arrays with the split data in it the arrays are not words. They turn out looking like this:
[[Ljava.lang.String;#4aa298b7, [Ljava.lang.String;#7d4991ad, [Ljava.lang.String;#28d93b30,...
[[Ljava.lang.String;#66d3c617, [Ljava.lang.String;#63947c6b, [Ljava.lang.String;#2b193f2d,...
This error seems to be specific to my code. I am using a text file not a manually entered array.
I am not sure what is happening to cause them to print out in this manner.
Any advice or corrections are greatly appreciated.
Here is my code currently:
import java.io.FileReader;
import com.opencsv.CSVReader;
import java.util.Arrays;
import java.util.ArrayList;
public class SATVocabPractice {
#SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
ArrayList words = new ArrayList(); //Word arrays
ArrayList definitions = new ArrayList(); //Definition arrays.
//Build reader instance
//Read data.csv
//Default seperator is comma
//Default quote character is double quote
//Start reading from line number 2 (line numbers start from zero)
CSVReader reader = new CSVReader(new FileReader("C:/Users/Brandon/Documents/NetBeansProjects/SAT Vocab Practice/src/sat/vocab/practice/Words.txt"), '|', '"', 0);
//Read CSV line by line and use the string array as you want
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null) {
//Verifying the read data here
System.out.println(Arrays.toString(nextLine));
definitions.add(Arrays.toString(nextLine).split("|"));
words.add(Arrays.toString(nextLine).split("\\|"));
}
}
System.out.println(words); //Print the word list
System.out.println(definitions); //Print the definitions
}
}
Try this:
System.out.println(Arrays.toString(words)); //Print the word list
System.out.println(Arrays.toString(definitions)); //Print the definitions
My suggestion:
The method Arrays.toString(nextLine) doesn't work how you expect it to.
Try to loop through nextLine and add each content of the array to definitions seperately
Preface: This is for an assignment in one of my classes.
I need to parse through a CSV file and add each string to an ArrayList so I can interact with each string individually with pre-coded functions.
My problem is that the final string in each line (which doesn't end with a comma) is combined with the first string in the next line and recognized as being at the same index in the ArrayList. I need to learn how to either add a line break or do something else that will stop my loop at the end of each line and read the next line separately. Perhaps there is a built-in method in the scanner class that I'm unaware of that does this for me? Help is appreciated!
Here is the information in the CSV file:
Fname,Lname,CompanyName,Balance,InterestRate,AccountInception
Sally,Sellers,Seashells Down By The Seashore,100.36,3,7/16/2002
Michael,Jordan,Jordan Inc.,1000000000,3,6/12/1998
Ignatio,Freely,Penultimate Designs,2300.76,2.4,3/13/1991
Here is my code so far
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("smalltestdata-sallysellers.csv"));
// Chomp off at each new line, then add to array or arraylist
scanner.useDelimiter("\n");
ArrayList<String> data = new ArrayList<String>();
while (scanner.hasNext()) {
// Grab data between commas to add to ArrayList
scanner.useDelimiter(",");
// Add grabbed data to ArrayList
data.add(scanner.next());
}
System.out.println(data.get(10));
scanner.close();
}
}
And here is the output
7/16/2002
Michael
It seems like you just need to do...
String s[] = scanner.nextLine().split(",");
Collections.addAll(data, s);