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.
Related
My code is too slow
How can I make my code efficiently? Currently the code needs several minutes until the file was read, which is way too long. Can this be done faster? There is no stacktrace, because it works, but too slow.
Thanks!
The Problem Code:
private void list(){
String strLine2="";
wwwdf2 = new StringBuffer();
InputStream fis2 = this.getResources().openRawResource(R.raw.list);
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis2));
if(fis2 != null) {
try {
LineNumberReader lnr = new LineNumberReader(br2);
String linenumber = String.valueOf(lnr);
int i=0;
while (i!=1) {
strLine2 = br2.readLine();
wwwdf2.append(strLine2 + "\n");
String contains = String.valueOf(wwwdf2);
if(contains.contains("itisdonecomplet")){
i++;
}
}
// Toast.makeText(getApplicationContext(), strLine2, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), wwwdf2, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use StringBuilder instead of StringBuffer.
StringBuffer is synchronized, and you don't need that.
Don't use String.valueOf, which builds a string, negating the value using a StringBuffer/Builder. You are building a string from the whole buffer, checking it, discarding the string, then constructing nearly the same string again.
Use if (wwwdf2.indexOf("itisdonecomplet") >= 0) instead, which avoids creating the string.
But this will still be reasonably slow, as although you would not be constructing a string and searching through it all, you are still doing the searching.
You can make this a lot faster by only searching the very end of the string. For example, you could use wwwdf2.indexOf("itisdonecomplet", Math.max(0, wwwdf2.length() - strLine2.length() - "itisdonecomplet".length())).
Although, as blackapps points out in a comment, you could simply check if strLine2 contains that string.
Don't use string concatenation inside a call to append: make two separate calls.
wwwdf2.append(strLine2);
wwwdf2.append("\n");
You don't check if you reach the end of the file. Check if strLine2 is null, and break the loop if it is.
My new Created code:(My test device is a Samsung S8)
private void list(){
String strLine2="";
wwwdf2 = new StringBuilder();
InputStream fis2 = this.getResources().openRawResource(R.raw.list);
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis2));
if(fis2 != null) {
try {
LineNumberReader lnr = new LineNumberReader(br2);
String linenumber = String.valueOf(lnr);
int i=0;
while (i!=1) {
strLine2 = br2.readLine();
wwwdf2.append(strLine2);
wwwdf2.append("\n");
if (wwwdf2.indexOf("itisdonecomplet") >= 0){
i++;
}
}
// Toast.makeText(getApplicationContext(), strLine2, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), wwwdf2, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
i have this code
public ArrayList<String> getMail() {
ArrayList<String> i = new ArrayList();
try {
int j = 0 ;
FileReader file = new FileReader("emaillist0.txt");
BufferedReader lerArq = new BufferedReader(file);
String linha = lerArq.readLine();
System.out.println("tp aqio ´prra");
while (linha != null) {
i.add(j, linha);
j++;
linha = lerArq.readLine();
}
System.out.println(i.size());
file.close();
return i;
} catch (IOException e) {
System.err.printf( e.getMessage());
return null;
}
}
this problem is when i execute this code in apache tomcat throws this error
emaillist0.txt (The system cannot find the file specified)java.lang.NullPointerException
but when i execute this code in a java application work perfectly
use absolute path instead of file's name, or move your file into bin directory of tomcat (of course it depends on your OS)
I'm working on a multiple choice quiz application in Android Studio, and inside a text file I have the answers to each question, as well as their corresponding questions. This is my first attempt at such a task, so apologies in advance for code that may be considered sloppy.
This is what I have for my text file:
Java, What language is most commonly used for Android application development?
Android Studio/Eclipse, Which of these programs is often used for Android application development?
2005, In what year did Google acquire Android?
(There are several more, but this should get the point across.)
The first string before the comma is what I'm trying to add to arrayListTerms, and the string following the comma to arrayListDef. Here's my code so far:
public class ActivityTwo extends AppCompatActivity {
int sizeOfArray;
String[][] qAndA;//Stores Questions and Answers
String[] temp;
ArrayList<String>arrayListTerms;
ArrayList<String>arrayListDef;
HashMap<String, String> qMatch = new HashMap<>();//Matches correct answer with current question
public static final String TAG =" ";
public ActivityTwo() {
arrayListDef = new ArrayList<>();
arrayListTerms = new ArrayList<>();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
InputStream myInputStream = this.getResources().openRawResource(R.raw.textfile);
BufferedReader myBufferedReader = new BufferedReader(new InputStreamReader(myInputStream));
String str = myBufferedReader.readLine();
while((str != null)) {
temp = str.split(",");
arrayListTerms.add(temp[0]);
arrayListDef.add(temp[1]);
//qMatch.put(temp[1], temp[0]);
}
Log.i(TAG, "Textfile Loaded.");
myBufferedReader.close();
} catch (FileNotFoundException ex) {
Log.e(TAG, "Unable to open text file.");
} catch (IOException ex){
Log.e(TAG, "Error reading text file.");
}
Collections.shuffle(arrayListDef);
sizeOfArray = arrayListDef.size();
Try using file.io to read the file, point it to the location, and you should be able to then upt the input from that into array list.
Change
while((str != null)) {
temp = str.split(",");
arrayListTerms.add(temp[0]);
arrayListDef.add(temp[1]);
//qMatch.put(temp[1], temp[0]);
}
To
String line = "";
while((line = str) != null) {
temp = line.split(",");
arrayListTerms.add(temp[0]);
arrayListDef.add(temp[1].trim()); //eliminate space after ','
//qMatch.put(temp[1], temp[0]);
}
You need to initialize an empty string then fill it in the while condition.
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
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).