Java - NoSuchMethodError on java.io.BufferdReader.lines on other systems - java

I'm using a small "xml text based database" to store information. While coding and debugging I had no problems with a method I created, but as an exe file(wrapped with jsmooth), it gives me an error:
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: java.io.BufferedReader.lines()LJava/util/stream/Stream:
at primary.loadErrorDB(primary.java:471
So i checked line 471 but on Intellij, there is no such error, everything works fine there.
Hope you guys know what to do.
This is the method
public static Object[] loadErrorDB() {
File db = new File(System.getProperty("user.dir") + "\\errordb.xml");
Object[] errordbAry = new String[20][20];
FileReader file = null;
try {
file = new FileReader(db);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
BufferedReader br = new BufferedReader(file);
Stream<String> streamList = br.lines();
errordbAry = streamList.toArray();
} catch (Exception ex) {
ex.printStackTrace();
}
String a = "";
for (Object o : errordbAry) {
a = a + String.valueOf(o) + ";";
}
String[] srgAry = a.split(";");
String[] newAry = new String[srgAry.length - 5];
int x = 0;
for (int i = 5; i < srgAry.length; i++) {
newAry[x] = srgAry[i];
x++;
}
return newAry;
}

br.lines(); <--BufferedReader don't have method lines() upto Java7 use readLine()
Update Java to Java8 to use this feature.
If You want to read one line at a time use
String line=br.readLine();
Before that make sure that file you are trying to read has line by null check.
String line=null;
if((line=br.readLine())!=null)
{//Go Ahead
}
See more one this from BufferedReader

http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--
BufferedReader.lines() was added in Java8. Check the version of Java that is being used after packaging with jsmooth.

The java.io.BufferedReader class in upto java 7 has readLine() but it dont have the lines() Refer the method. But in java 8 java.io.BufferedReader has the lines() refer for java 8
So first of all check which version of java you have and then proceed accordingly

Related

GWT: reading from a CSV file on the Server

I try to convert an old Applet to a GWT Application but I encountered a problem with the following function:
private String[] readBrandList() {
try {
File file = new File("Brands.csv");
String ToAdd = "Default";
BufferedReader read = new BufferedReader(new FileReader(file));
ArrayList<String> BrandName = new ArrayList<String>();
while (ToAdd != null) {
ToAdd = (read.readLine());
BrandName.add(ToAdd);
}
read.close();
String[] BrandList = new String[BrandName.size()];
for (int Counter = 0; Counter < BrandName.size(); Counter++) {
BrandList[Counter] = BrandName.get(Counter);
}
return BrandList;
} catch (Exception e) {
}
return null;
}
Now apparently The BufferedReader isn't supported by GWT and I find no way to replace it other than writing all entries into the code which would result in a maintenance nightmare.
Is there any function I'm not aware of or is it just impossible?
You need to read this file on the server side of your app, and then pass the results to the client using your preferred server-client communication method. You can read and pass the entire file, if it's small, or read/transfer in chunks if the file is big.

Java extract text from text file from a certain point on the text

I have created a method with BufferedReader that opens a text file created previously by the program and extracts some characters. My problem is that it extracts the whole line and I want to extract only after a specified character, the :.
Here is my try/catch block:
try {
InputStream ips = new FileInputStream("file.txt");
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br1 = new BufferedReader(ipsr);
String ligne;
while((ligne = br1.readLine()) != null) {
if(ligne.startsWith("Identifiant: ")) {
System.out.println(ligne);
id = ligne;
}
if(ligne.startsWith("Pass: ")) {
System.out.println(ligne);
pass = ligne;
}
}
System.out.println(ligne);
System.out.println(id);
System.out.println(pass);
br1.close();
} catch (Exception ex) {
System.err.println("Error. "+ex.getMessage());
}
At the moment, I return to my String id the entire ligne, and same for pass – by the way, all the sysout are tests and are useless there.
If anybody knows how to send to id the line after the :and not the entire line, I probably searched bad, but google wasn't my friend.
Assuming there's only one : symbol in the string you can go with
id = ligne.substring(ligne.lastIndexOf(':') + 1);
Use StringUtils
StringUtils.substringAfter(id ,":"),
Why don't you try to do a split() on ligne?
If you use String[] splittedLigne = ligne.split(":");, you will have the following in splittedLigne:
splittedLigne[0] -> What is before the :
splittedLigne[1] -> What is after the :
This will give you what you need for every line. Also, this will work for you if you have more than one :.

Parsed strings from .csv-file are invalid tokens in an kml-file. How can i solve this?

I have a code which parses strings from an CSV.-file (with twitter data) and gives them to a new KML file. When i parse the comments from the twitter data there are of course unknown tokens like: 🚨. When i open up the new KML-File in Google Earth i get an error because of this unknown tokens.
Question:
When i parse the strings, can i tell java it should throw out all unknown tokens from the string so that i don't have any unknown tokens in my KML?
Thank you
Code below:
String csvFile = "twitter.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
String[] twitter = null;
int row_desired = 0;
int row_counter = 0;
String[] placemarks = new String[1165];
// ab hier einlesen der CSV
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (row_counter++ == row_desired) {
twitter = line.split(cvsSplitBy);
placemarks[row_counter] =
"<Placemark>\n"+
"<name>User ID: "+twitter[7]+"</name>\n"+
"<description>This User wrote: "+twitter[5]+" at the: "+twitter[6]+"</description>\n"+
"<Point>\n"+
"<coordinates>"+twitter[1]+","+twitter[2]+"</coordinates>\n"+
"</Point>\n"+
"</Placemark>\n";
row_desired++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
for(int i = 2; i <= 1164;i++){
String kml2 = kml.concat(""+placemarks[i]+"");
kml=kml2;
}
kml = kml.concat("</Document></kml>");
FileWriter fileWriter = new FileWriter(filepath);
fileWriter.write(kml);
fileWriter.close();
Runtime.getRuntime().exec(googlefilepath + filepath);
}
Text files are not all built equal: you must always consider what character encoding is in use. I'm not sure about Twitter's data specifically, but I would guess they're doing like the rest of the world and using UTF-8.
Basically, avoid FileReader and instead use the constructor of InputStreamReader which lets you specify the Charset.
Tip: if you're using Java 7+, try this:
for (String line : Files.readAllLines(file.toPath(), Charset.forName("UTF-8"))) { ...
More Info
The javadoc of FileReader states "The constructors of this class assume that the default character encoding"
You should avoid this class, always. Or at least for any data that might ever be transferred between computers. Even a program running on Windows "using the default charset" will assume UTF-8 when run from inside Eclipse, or ISO_8859_1 when running outside Eclipse! Such non-determinism from a class is not good.

Unusual output from using split()

I'm reading from a file that has the following format:
name : symptoms : causes : treatments : rate : prognosis
There are a total of 21 entries but when I try to read from the file and use .split(":");, the output changes each time but is always along the lines of: [Ljava.lang.String;#614951ff. I'm guessing it's the pointer or memory address but I want the String value. I'm not getting any exceptions though so I'm not sure where I've gone wrong. The purpose of the method is to read the file and split into an array using the delimiter for the given file row selected.
public String[] readCancer(int row) {
cancers = new String[22];
FileInputStream fis;
InputStreamReader isr;
BufferedReader br = null;
String eachCancer;
String[] splitCancer = null;
int j = 0;
try {
fis = new FileInputStream(myData);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
input = new Scanner(br);
while(input.hasNext() && j < 23) {
cancers[j++] = input.nextLine();
}
eachCancer = cancers[row].toString();
splitCancer = eachCancer.split(":");
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem with file input");
} finally {
try {
if(br != null) {
br.close();
}
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem closing the file");
}
}
return splitCancer;
}
To print the contents of array :
1) System.out.println(Arrays.deepToString(splitCancer));
2) System.out.println(Arrays.toString(splitCancer));
3) System.out.println(Arrays.asList(splitCancer));
If you want to display the string array, you should use:
System.out.println(Arrays.toString(splitCancer));
Because when you print splitCancer you'll get the address of the array and not the content of it.
Of course you can print the content in other ways:
for(String str : splitCancer) {
System.out.println(str);
}
Currently I have the following:
public String[] readCancer() {
cancers = new String[22];
split = new String[22];
FileInputStream fis;
InputStreamReader isr;
BufferedReader br = null;
String eachCancer;
int j = 0;
try {
fis = new FileInputStream(myData);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
input = new Scanner(br);
while(input.hasNext() && j < 23) {
cancers[j] = input.nextLine().toString();
//cancers[j] = input.nextLine();
split[j] = cancers[j].split(":");
//split[j] = "blah"; this line works
j++;
}
System.out.println(Arrays.toString(split));
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem with file input");
} finally {
try {
if(br != null) {
br.close();
}
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem closing the file");
}
}
return split;
//return split[j]; does not work
}
In my while loop, I keep getting compile errors saying it requires a String but found Stirng[] for split. When I try something simpler, such as split[j] = "blah";, there are no compile errors. I can return cancers perfectly but I need to split by the : delimiter and that seems to be something I cant get my head around. When I try return split[j], then I get another compile error saying it requires a String[] but found String. I've been at this for more than an hour, read through examples in my textbook and tutorials online for using split but it still isn't working. This is the only part of my program that I'm not sure how to do.
I tried pasting the entire file but it came a horrid block of text, so here are 2 lines from it. Each line has the same format but differing lengths:
The general format of the file is name : symptoms : causes : treatment : rate : prognosis
The rate is a String since it is unknown for some diseases and when it is known, the rate is not always out of 250,000. Sometimes it is out of 1,000,000 or 100,000, etc... .
acute promyelocytic leukemia : easy bruising, rapid internal bleeding, fatigue, anemia, frequent fever, infection, blood clots : PML and RARA genes : Medications, chemotherapy : 1 in 250,000 : Good
familial cylindromatosis : numerous skin tumours, ulcers, infection, impaired eyesight, hearing, smell, balance : CYLD gene : Surgery, chemotherapy : Unknown : Unknown
My most recent code attempt is at Unusual output from using split()
The 2 arrays of cancers and split are private String[] as field variables declared outside any of the methods. The variable myData is a private File also declared as a field variable outside any of the methods. I have checked and already verified the file path is correct.
The main method that calls the method:
public static void main(String[] args) {
CancerGUI _gui = new CancerGUI();
String[] resultCancer;
resultCancer = _gui.readCancer();
//System.out.println(resultCancer);
System.out.println(Arrays.toString(resultCancer));
}
I am only calling it in the main method to test whether it correctly returns the String[]. Once it does, then I will call it in a different method that adds the data to a GUI (this part I am reasonably confident I know how to do and have examples from my instructor and textbook to follow).

Import Textfile and read line by line in Java

I was wondering how one would go about importing a text file. I want to import a file and then read it line by line.
thanks!
I've no idea what you mean by "importing" a file, but here's the simplest way to open and read a text file line by line, using just standard Java classes. (This should work for all versions of Java SE back to JDK1.1. Using Scanner is another option for JDK1.5 and later.)
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(fileName)));
try {
String line;
while ((line = br.readLine()) != null) {
// process line
}
} finally {
br.close();
}
This should cover just about everything you need.
http://download.oracle.com/javase/tutorial/essential/io/index.html
And for a specific example: http://www.java-tips.org/java-se-tips/java.io/how-to-read-file-in-java.html
This might also help: Read text file in Java
I didnt get what you meant by 'import'. I assume you want to read contents of a file. Here is an example method that does it
/** Read the contents of the given file. */
void read() throws IOException {
System.out.println("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new File(fFileName), fEncoding);
try {
while (scanner.hasNextLine()){
text.append(scanner.nextLine() + NL);
}
}
finally{
scanner.close();
}
System.out.println("Text read in: " + text);
}
For details you can see here
Apache Commons IO offers a great utility called LineIterator that can be used explicitly for this purpose. The class FileUtils has a method for creating one for a file: FileUtils.lineIterator(File).
Here's an example of its use:
File file = new File("thing.txt");
LineIterator lineIterator = null;
try
{
lineIterator = FileUtils.lineIterator(file);
while(lineIterator.hasNext())
{
String line = lineIterator.next();
// Process line
}
}
catch (IOException e)
{
// Handle exception
}
finally
{
LineIterator.closeQuietly(lineIterator);
}

Categories

Resources