Read file from txt and split string using comma - java

Why is it it says that there is no split method found ? I want to split one lines to several parts. But there is error. Why is that so ?
try {
Scanner a = new Scanner (new FileInputStream ("product.txt"));
while (a.hasNext()){
System.out.println(a.nextLine()); //this works correctly, all the lines are displayed
String[] temp = a.split(",");
}
a.close();
}catch (FileNotFoundException e){
System.out.println("File not found");
}

split() is not defined for Scanner but for String.
Here's a quick fix:
String line = a.nextLine();
System.out.println(line); //this works correctly, all the lines are displayed
String[] temp = line.split(",");

split method works on the String and not on the Scanner. So store the contents of
a.nextLine()
in a string like this
String line = a.nextLine();
and then use split method on this stirng
String[] temp = line.split(",");

Related

Read text from file line by line to 2 strings variables

I have a file with some words saved in a text file like that:
Koraa
Orakaa
Balaes
Ealaaab
Araqko
I need to know how to read it using Java like below:
string firstWord = "Koraa";
and the 2nd line in another string
string secondWord = "Orakaa";
then I will do some stuff on those 2 strings then secondWord & firstWord contents' will be replaced with next 2 lines in the same file !
for example:
firstWord = "Balaes";
secondWord = "Ealaaab";
... etc the operation will be looping on all these words.
You can have an ArrayList of String and read separate lines from a file using Scanner.
List<String> al = new ArrayList<String>();
File file = new File("example.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
al.add(scanner.nextLine())
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
You can refer to the individual words, in order, with al.get(int index).

Java Scanner Split Strings by Sentences

I am trying to split a paragraph of text into separate sentences based on punctuation marks i.e. [.?!] However, the scanner splits the lines at the end of each new line as well, even though I've specified a particular pattern. How do I resolve this? Thanks!
this is a text file. yes the
deliminator works
no it does not. why not?
Scanner scanner = new Scanner(fileInputStream);
scanner.useDelimiter("[.?!]");
while (scanner.hasNext()) {
line = scanner.next();
System.out.println(line);
}
I don't believe the scanner splits it on line breaks, it is just your "line" variables have line breaks in them and that is why you get that output. For example, you can replace those line breaks with spaces:
(I am reading the same input text you supplied from a file, so it has some extra file reading code, but you'll get the picture.)
try {
File file = new File("assets/test.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[.?!]");
while (scanner.hasNext()) {
String sentence = scanner.next();
sentence = sentence.replaceAll("\\r?\\n", " ");
// uncomment for nicer output
//line = line.trim();
System.out.println(sentence);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
This is the result:
this is a text file
yes the deliminator works no it does not
why not
And if I uncomment the trim line, it's a bit nicer:
this is a text file
yes the deliminator works no it does not
why not

Split text files

First of all I am new to Java.
I am trying to use the Split() function on a user specified txt file.
It should split the files using space to output a array of Strings.
I am using JFileChooser but I dont know how to perform Split on the selected txt file. I am using a Scanner to do this.
Please if someone can make the code finished, for some reason I cant get my head around it :-/
I have made it so far:
JFileChooser chooser = new JFileChooser("C:\\");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
".txt and .java files", "txt", "java");
chooser.setFileFilter(filter);
int code = chooser.showOpenDialog(null);
if (code == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
Scanner input;
try {
input = new Scanner(selectedFile);
while (input.hasNext()) {
String[] splits = input.next().split(" ");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If you need to split the input by the space character, then include a string with a space instead of an empty string. Replace
String[] splits = f.split("");
with
String[] splits = f.split(" "); // One space
As others have pointed out, f isn't declared in your block. You'll have to declare it as a String and use your Scanner to read input into f, then use split.
f.split("");
or
f.split("[\\s]+");
to be safe with tabs and double spaces.
What is f? It's not declared anywhere, except as an Exception after having being used earlier, which makes no sense.
Your while loop should be written as this:
while (input.hasNextLine()) {
String line = input.nextLine();
String[] splits = line.split(" ");
// put the result of split somewhere
}
while (input.hasNext()) {
String[] splits = f.split("");
input.next();
}
System.out.println(f);
First of all, splits is never used. Second of all, input.next() is never stored in a variable. Also, I have no idea what f is. Try something like this:
while (input.hasNext()) {
String[] splits = input.next().split(" ");
someList.add(splits);
}
You could declare someList as something like new ArrayList<String[]>().

Processing a string of information

I have a text file that holds baseball teams as YEAR:TEAM1:POINTS1:TEAM2:POINTS2 on each line.
How can I process it so that I wind up with the year, 1st team's name, and if they won or not?
I know I should use delimiter \n and : to separate the data, but how can I actually keep track of the info that I need?
Since this is homework, here is not the solution, but just some hints:
Have a look at the class StringTokenizer to split the line.
Have a look at InputStreamReader and FileInputStream to read the file.
Have a look at the String class's split method.
To split the text you can use the methods String#indexOf(), String#lastIndexOf() and String#subString.
Then to compare which team has one, I would convert the String into an int and then compare the two values.
How about a healthy serving of Regex?
try something like this
public static void readTeams() throws IOException{
try {
fstream = new FileInputStream("yourPath");
in = new DataInputStream(fstream);
br = new BufferedReader(new InputStreamReader(in));
String s = br.readLine();
String[] tokens = s.split(":");
while(s!=null){
for (String t : tokens){
System.out.println(t);
}
}
in.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(YourClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is an example found at java-examples.com
String str = "one-two-three";
String[] temp;
/* delimiter */
String delimiter = "-";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
/* print substrings */
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);//prints one two three on different lines
Now for reading the input you can use BufferedReader and FileReader check examples for that on google.

Read next word in java

I have a text file that has following content:
ac und
accipio annehmen
ad zu
adeo hinzugehen
...
I read the text file and iterate through the lines:
Scanner sc = new Scanner(new File("translate.txt"));
while(sc.hasNext()){
String line = sc.nextLine();
}
Each line has two words. Is there any method in java to get the next word or do I have to split the line string to get the words?
You do not necessarily have to split the line because java.util.Scanner's default delimiter is whitespace.
You can just create a new Scanner object within your while statement.
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("translate.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
System.out.println(s);
}
}
You already get the next line in this line of your code:
String line = sc.nextLine();
To get the words of a line, I would recommend to use:
String[] words = line.split(" ");
Using Scanners, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().
On the other hand, If you split by space (line.split(" ")), the code will fail if you try to read a file with a different whitespace delimiter. If split() expects you to write a regular expression, and it does matching anyway, use split("\\s") instead, that matches a "bit" more whitespace than just a space character.
P.S.: Sorry, I don't have right to comment on already given answers.
you're better off reading a line and then doing a split.
File file = new File("path/to/file");
String words[]; // I miss C
String line;
HashMap<String, String> hm = new HashMap<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")))
{
while((line = br.readLine() != null)){
words = line.split("\\s");
if (hm.containsKey(words[0])){
System.out.println("Found duplicate ... handle logic");
}
hm.put(words[0],words[1]); //if index==0 is ur key
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can just use Scanner to read word by word, Scanner.next() reads the next word
try {
Scanner s = new Scanner(new File(filename));
while (s.hasNext()) {
System.out.println("word:" + s.next());
}
} catch (IOException e) {
System.out.println("Error accessing input file!");
}

Categories

Resources