Infinite loop during file reading and String.split() not working properly - java

I have a text file admin.dat which looks like this:
blackranger|sdasdasdasd23123|1000
blueranger|sdasdasdasdwhhh22|1000
brownranger|lppsadospd123|1000
I am trying to read every line, using | as my delimiter and outputting to the console every section.
Code:
package testing;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
Scanner filereader = null;
try {
filereader = new Scanner(new File("./src/testing/players.dat"));
String data;
while(filereader.hasNextLine()) {
String foo = "abc|123|a213";
String[] bar = foo.split("|");
for (int i = 0; i < 3; i++) {
System.out.println(bar[i]);
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error while reading file");
} finally {
if (filereader != null) {
filereader.close();
}
}
}
}
Expected Outcome:
blackranger
sdasdasdasd23123
1000
blueranger
sdasdasdasdwhhh22
1000
brownranger
lppsadosph123
1000
Actual Outcome:
a // infinite loop
b
a
b
a
b
a
b
a
b
Why am I getting an infinite loop which prints a b forever?

You should escape the character | because it has special meaning in regex
foo.split("\\|");
But firstly, assign foo with value that you read from the file, not by hard-coded it:
String foo = filereader.nextLine();

You never read from the fileReader inside the while loop, so while(filereader.hasNextLine()) will always be true, and it makes sense that the loop will never end. What surprised me is that it looked like you had code that did read from the fileReader inside of the loop but commented it out. Why?
Solution: don't do this. Make sure to change the test condition inside the while loop, else the while loop will never end.

String foo = filereader.nextLine();
String[] bar = foo.split("\\|");
instead of
String foo = "abc|123|a213";
String[] bar = foo.split("|");

Related

Search in a text file (with specific pattern)

The text file looks something like this:
keyword12x:
=========
Acon:
a1
x2
z3
Bcon:
c1
e2
w3
r4
and so on... (always the same sheme and a lot of keywords in the file)
I need a function that I can pass keyword12x and the signal type that I'm looking for which searches through the text file and returns the corresponding Acon or Bcon singnals
Exaple declaration:
public string searchKey(string keyword, string type){
....
}
a call like:
search("keyword12x", "Acon")
outputs:
a1
x2
z3
(type = Bcon would obviously give c1, e2, w3, r4)
EDIT: This is what "I have".. (It's not what I want and only for testing porpose)
As you can see it's searching the "keyword12x" line and I'm stuck there.
import java.io.File;
import java.util.Scanner;
public class ReadText
{
public static void main(String[] args) throws Exception
{
File file =
new File("C:\\test.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()){
String line = sc.nextLine();
if(line.contains("keyword12x")){
System.out.println(line);
}
}
}
}
EDIT2:
> step by step "in english":
> 1. go trough lines
> 2. untill you find "keyword12x"
> 3. keep going through lines (from that point !)
> 4. find "Acon:"
> 5. go next line
> 6. start printing out and go next line (loop)
> 7. until line = "Bcon:" appears
> 8. go next line
> 9. start printing out and go next line (loop)
> 10. untill an empty line appears
EDIT3:
Lets resume: I want to search for a line containing the keyword (with a ':' appended), then (after that line) search for a line containing the given type (also followed by ':') and then gather all following lines up to, but not including a line that ends with ':' or empty line. [summary by #Carlos Heuberger]
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Demo
{
static String readLine = "";
String ch ;
static File f = new File("/home/admin1/demoEx");
public String searchKey(String keyword, String type) throws IOException
{
ch = type.toLowerCase().substring(0, 1);
BufferedReader b = null;
try {
b = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Reading file using Buffered Reader");
while ((readLine = b.readLine()) != null)
{
if(readLine.contains(ch))
{
System.out.println(readLine);
}
}
return readLine;
}
public static void main(String args[])
{
try {
String x = (new Demo()).searchKey("keyword12x","Bcon");
} catch (IOException e) {
e.printStackTrace();
}
}
}
try this one.

Output not printing to txt file Java

I am trying to create a program which prints out all the possible combinations of the letters "AUGC".
The output would really print to a txt file and the result would be a txt file with something like this:
"AAA
AAG
AAC
AAU
AGA"
etc
Here is the code I have so far:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Permute {
static String s = "ACGU";
static void permute(int level, String prefix) {
if (level == 0) {
String fileName = "out.txt";
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(fileName);
outputStream.println(prefix);
System.out.println(prefix);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return;
}
for (int i = 0; i < s.length(); i++) {
permute(level - 1, prefix + s.charAt(i));
}
}
public static void main(String[] args) {
int k = 2;
permute(k, "");
}
}
Currently the program is printing all the output to the console and only the last permutation to the txt file.
I would like it to print all the information to both.
Any help would be greatly appreciated
You are closing OutputStream prematurely. Since you are using recursion, pass OutputStream as a parameter to permute method from main method. Initialize stream and close it in main method.
I maybe wrong on this one but do you not need to include a "\n" as part of your outputStream.println(prefix);
so that is looks like
outputStream.println(prefix + "\n");
This will help as it seems to replacing the line with the newest details and not on a new line which is what you seem to be looking for.

Bufferedreader throws NullPointerException inside of a loop [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
My code is supposed to read a file line by line, to put each one in a string array named: tuples, (tuples=ligne.split(" "); ) and then add this tuples to an arraylist, one line read = one element of the arraylist.
Unfortunately, my code doesn't work! My buffered reader throws a NullPointerException in my loop!
Error returned in the ExtractFile() method, line 120: tuples= ligne.split(" ");
File file = new File("Department.txt");
BufferedReader in;
PrintWriter out;
String ligne;
int nbCols; //number of metadatas in my file.txt
String metadata[] = new String[nbCols];
String[] tuples = new String[nbCols];//1ere case indique num ligne
ArrayList<String[]> itemset = new ArrayList<String[]>();
public ArrayList ExtractionFile () {
try {
int i = 1;
in = new BufferedReader(new FileReader(file));
while ((ligne = in.readLine()) != null) {
while (ligne.charAt(0) != '1') {
ligne = in.readLine();//browse until line 1 is found
}
tuples = ligne.split(" ");
itemset.add(tuples);
System.out.println(Arrays.toString(itemset.get(0)));
for (i = 2; i < TuplesCount(); i++) {
ligne = in.readLine();
tuples = ligne.split(" ");// THIS LINE THROWS THE EXCEPTION
itemset.add(tuples);
System.out.println(Arrays.toString(itemset.get(i)));
}
}
} catch (IOException es) {
es.printStackTrace();
} catch (ArrayIndexOutOfBoundsException exepti) {
exepti.printStackTrace();
}
return itemset;
}
A NullpointerException tells you that your code
attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object.
...
In your case, you've told us that the error occurs on
tuples = ligne.split(" ");
You're trying to call split on ligne and - given the documentation quote above - that implies that ligne is null at that point.
It's worth noting that it is the second occurence of that line that throws the Exception, so it is not as simple as the file not having a line that starts with 1
Why?
You need to use a debugger or use lots of System.out.println to convince yourself how the value of ligne changes as your code executes and, crucially, where it becomes null.
In your case - we don't know what TuplesCount() returns, but the likelihood is that you keep iterating in that loop beyond the end of the file, so the line immediately before the one that fails
ligne = in.readline();
can return null and you never check for that at that point. Note that conditions for the loops are only checked after each iteration of the loop - so , except for the one right at the top in the condition of the while loop, all the calls to ligne = in.readline(); could return null and are never checked.
The code you provide us is really unreadable and should be formatted to easy debug it. Instead, you can try this simple code that i have tested on my IDE
package example;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class FileSplit {
public static void main(String[] args) {
ArrayList<String[]> phrases = new ArrayList<String[]>();
try{
BufferedReader in = new BufferedReader(new FileReader("Department.txt"));
String s;
while((s = in.readLine()) != null){
String[] words = s.split(" ");
phrases.add(words);
}
}catch(Exception e){
e.printStackTrace();
}
for(int i=0;i<phrases.size();i++){
for(int j=0;j<phrases.get(i).length;j++)
System.out.println(phrases.get(i)[j]);
}
}
}
Are you testing this with a file which doesn't contain a line 1? If so, you run this it will keep executing the inner loop despite the fact that the value is null, resulting in an exception the time after the last line has been read. To fix this change the inner loop to be an if.
Like so:
public ArrayList ExtractionFile() {
try {
int i = 1;
in = new BufferedReader(new FileReader(file));
ligne = in.readLine(); //It can be more readable to seperate the assignment and the condtion
while (ligne != null) {
if (ligne.charAt(0) != '1') {
ligne = in.readLine();//browse until line 1 is found
} else {
tuples = ligne.split(" ");
itemset.add(tuples);
System.out.println(Arrays.toString(itemset.get(0)));
for (i = 2; i < TuplesCount(); i++) {
ligne = in.readLine();
tuples = ligne.split(" ");// CETTE LIGNE SOULEVE L EXCEPTION
itemset.add(tuples);
System.out.println(Arrays.toString(itemset.get(i)));
}
}
}
} catch (IOException es) {
es.printStackTrace();
} catch (ArrayIndexOutOfBoundsException exepti) {
exepti.printStackTrace();
}
return itemset;
}
private int TuplesCount() {
return Arrays.asList(tuples).size();
}
public static void main(String[] args){
Main main = new Main();
main.ExtractionFile();
}
}
As per some of the points above, please do format your code - it makes it easier to get help! Also, read up on breakpoints!

BufferedReader sometimes read text, sometimes doesn't

I'm trying to read from a .java the methods I have on it, also the classes, I'm using taggs to identify them and stored them, the problem is that using BufferedReader sometimes just doesn't work, the buffer skips a lot of lines for a reason that I can't understand, sometimes when checking the file by myself I just put random spaces between lines, and that fixes some parts, but I can't get the Buffer read all my text without skipping anything, my code so far is like this:
public class ReadFile {
public static void main(String[] args) {
int numclas=0,numbase=0,numbaseagr=0,numbmet=0,numag=0;
String mt="//MT";
String[] nomclass2 = new String[10];
String[] nommetodo2 = new String[50];
boolean metodo=false;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("\\Program.java"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.trim().split("\\s+");
for(int i=0;i<splited.length;i++){
System.out.println(splited[i]);
if(splited[i].equals("class")){
nomclass2[numclas]=splited[i+1];
numclas=numclas+1;
}
if (splited[i].equals(mt)){
metodo=true;
}
if (splited[i].equals("public")){
if (splited[i+1].equals("static")){
nommetodo2[numbmet]=splited[i+3];
numbmet=numbmet+1;
}
if (splited[i+1].equals("int")||splited[i+1].equals("double")||splited[i+1].equals("String")||splited[i+1].equals("boolean")){
nommetodo2[numbmet]=splited[i+2];
numbmet=numbmet+1;
}
if (splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean")){
nommetodo2[numbmet]=splited[i+1];
numbmet=numbmet+1;
}
metodo=false;
}
if ((splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean"))&&metodo){
nommetodo2[numbmet]=splited[i+1];
numbmet=numbmet+1;
metodo=false;
}
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
Now let me show you the .java I'm trying to read:
import java.text.DecimalFormat;
import java.io.*;
//Main file of the program 1
public class Program1 {
//MT
public static void main (String args []) {
DecimalFormat format=new DecimalFormat("##.##");
System.out.println("How many data do you want to insert?");
int num=Leer.Int();
Fila lista=new Fila();
Fila lista2=new Fila();
double x=0.0;
for(int i=0;i<num;i++){
x=Leer.Double();
lista.addNum(x);
}
double prom=0.0;
double desv=0.0;
prom=lista.getprom();
desv=lista.getdevst();
System.out.println("The mean for column 1 is: "+format.format(prom));
System.out.println("The Std.Dev for column 1 is: "+format.format(desv));
System.out.println("How many data do you want to insert?");
num=Leer.Int();
x=0.0;
for(int i=0;i<num;i++) {
x=Leer.Double();
lista2.addNum(x);
}
prom=0.0;
desv=0.0;
prom=lista2.getprom();
desv=lista2.getdevst();
System.out.println("The mean for column 2 is: "+format.format(prom));
System.out.println("The Std.Dev for column 2 is: "+format.format(desv));
}
}
And the result when I print the array
Date:
12/12/12
import
java.text.DecimalFormat;
//Main
file
of
the
program
1
//MT
DecimalFormat
format=new
DecimalFormat("##.##");
so on...
See how in the //MT the Buffer skips a lot of lines, a lot of this is happening (see how it ignores the first lines of the program), and I don't know how to fix it, because sometimes when I try to "fix it" and add some spaces in the lines, I get a nullpointer and the program ends.
Any help will be appreciated, thank you.
This is just a partial answer - at the very least your program is skipping every other line:
while ((read = in.readLine()) != null)
will read a line from the file. The line is immediately discarded because the immediately following statement:
read = in.readLine();
reads and processes the next line from the file.
(also, 'splited' should be 'splitted' along with numerous other spelling mistakes but they're not really affecting your program, just it's readability :-))

How can I parse through a file for a string matching a generated string?

My bad for the title, I am usually not good at making those.
I have a programme that will generate all permutations of an inputted word and that is supposed to check to see if those are words (checks dictionary), and output the ones that are. Really I just need the last the part and I can not figure out how to parse through a file.
I took out what was there (now displaying the "String words =") because it really made thing worse (was an if statement). Right now, all it will do is output all permutations.
Edit: I should add that the try/catch was added in when I tried turning the file in a list (as opposed to the string format which it is currently in). So right now it does nothing.
One more thing: is it possible (well how, really) to get the permutations to display permutations with lesser characters than entered ? Sorry for the bad wording, like if I enter five characters, show all five character permutations, and four, and three, and two, and one.
import java.util.List;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import static java.lang.System.out;
public class Permutations
{
public static void main(String[] args) throws Exception
{
out.println("Enter anything to get permutations: ");
Scanner scan = new Scanner(System.in);
String io = scan.nextLine();
String str = io;
StringBuffer strBuf = new StringBuffer(str);
mutate(strBuf,str.length());
}
private static void mutate(StringBuffer str, int index)
{
try
{
String words = FileUtils.readFileToString(new File("wordsEn.txt"));
if(index <= 0)
{
out.println(str);
}
else
{
mutate(str, index - 1);
int currLoc = str.length()-index;
for (int i = currLoc + 1; i < str.length(); i++)
{
change(str, currLoc, i);
mutate(str, index - 1);
change(str, i, currLoc);
}
}
}
catch(IOException e)
{
out.println("Your search found no results");
}
}
private static void change(StringBuffer str, int loc1, int loc2)
{
char t1 = str.charAt(loc1);
str.setCharAt(loc1, str.charAt(loc2));
str.setCharAt(loc2, t1);
}
}
If each word in your file is actually on a different line, maybe you can try this:
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null)
{
... // check and print here
}
Or if you want to try something else, the Apache Commons IO library has something called LineIterator.
An Iterator over the lines in a Reader.
LineIterator holds a reference to an open Reader. When you have finished with the iterator you should close the reader to free internal resources. This can be done by closing the reader directly, or by calling the close() or closeQuietly(LineIterator) method on the iterator.
The recommended usage pattern is:
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
it.close();
}

Categories