I cannot understand why this keeps crashing with a memory error:
server = new URL("http://-link cannot be supplied-");
BufferedReader reader2 = read(server);
line = reader2.readLine();
StringBuilder bigString = new StringBuilder("");
while(line!=null) {
bigString.append(line);
reader2.readLine();
}
the file is not -that- big 7000 odd lines # 240,031 bytes on disk.
Basically what i need to do is to tell wether the file contains a small string (a postcode) the file is basically a list of postcodes.
What is the best way to read this in? as obviously what i am doing is not working at all :D
Your while loop never ends!
while(line!=null) {
bigString.append(line);
line = reader2.readLine();
}
should work.
Related
So I was trying to read a text file of approx 40KB using Buffered Reader in android. The thing is one of the line (mostly last line) from the file exceeds 9000 characters which is difficult to store in String and to log it.
I tried this approach below but as characters exceed it discards parsing the remaining part from the line.
try {
File root = android.os.Environment.getExternalStorageDirectory();
File file = new File (root.getAbsolutePath() + "/" + "new.txt");
BufferedReader r = null;
r = new BufferedReader(new FileReader(file));
StringBuilder total = new StringBuilder();
String line;
while((line = r.readLine()) != null) {
Log.e("Line",line);
total.append(line);
}
r.close();
} catch (Exception e) {
e.printStackTrace();
}
To which I thought to change String line to String line = new String(new byte[1024*1024]) could solve my problem. But Android Studio is highlighting this as reductant code. The thing is I need to apply some regex stuff on each line in while loop.
Is there any workaround I can use. By the way here is my 40 KB file link https://www.dropbox.com/s/hp7vn6vt86adv6g/new.txt?dl=0
Edit: The file I am trying to parse is an html file.
Updated
I was wrong, the string in the line is not omitting the rest part as suggested by skandigraun (from comments). Logger was not printing the whole string because it was exceeding it's 4000 chars limit while my string was 8093 chars.
In short above code is working just as fine!
Is it possible to read a textfile on sdcard during runtime of an UIautomator test? As in an android application, using getExternalDirectory() etc. to create a File-object pointing to the actual file. Is it possible to send a command using getRuntime().exec("cmd"), if so, how? Or is there an easier way to simply access the device:s sdcard and read a file into the test?
The goal is to throughout the test send parameters to the test. So the test will perform certain actions, then continously look for a change on a file on the devices sdcard, and if so, read that line, and continue to perform actions. So therefor a way to read a file, and check certain things, is needed.
Or is there perhaps another way to pass information into the test during runtime? I know it can be done at the start of the testrun, but not during testrun.
I use below code inside uiautomator code to read text files.instead of
public void FileRead(String file_location) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file_location));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
//you can do whatever you want here or return String
} finally {
br.close();
}
}
This should be straight forward but for some reason when I try to count words in a file after I download it to my SD Card, the number seems to be off. Also the more occurrences there are, the further my result seems to be off. I use Microsoft Word to verify the number of occurrences (using ignore case and whole word only). To test the number of occurrences, I use the "the_counter" variable below. I also verified there is nothing wrong with download & the FULL file is downloaded to my SD card. This is driving me nuts -- I'm thinking Word cannot be wrong here so what could possibly be wrong with my code below?
Could it be white space or special chars in the file causing the problem --is there a way to clean the file to verify this?
//Find the directory for the SD Card using the API
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,TEMP_FILE);
//Read text from file
//StringBuilder text = new StringBuilder();
m_tree = new Tree();
int i=0;
BufferedReader br = null;
long the_counter=0;
try {
br = new BufferedReader(new FileReader(file));
String line;
String []arLine;
while ((line = br.readLine()) != null) {
//get each word in line
if(line.length()==0)
continue;
arLine = line.split("\\s+");
//now add each word to search tree
for(i=0;i< arLine.length;++i){
m_tree.insert(arLine[i]);
if(arLine[i].equalsIgnoreCase("a"))
++the_counter;
}
}
m_sTest = Long.toString(the_counter) ;
br.close();
I edited my code to read in each character per line and create words manually. and I STILL GET THE SAME RESULT.
br = new BufferedReader(new FileReader(file));
String line;
String []arLine;
StringBuilder word = new StringBuilder();
while ((line = br.readLine()) != null) {
//check for word at end of last line
if(word.length()>0){
m_tree.insert(word.toString());
word.setLength(0);
}
char[] lineChars = new char [line.length()];
line.getChars(0,line.length(),lineChars,0);
for(char c: lineChars){
if(c== ' '){
//if we have a word then store and clear then move on
if(word.length()>0){
m_tree.insert(word.toString());
word.setLength(0);
}
}
else{
word.append(c);
}
}
This is issue was that I was not accounting for special characters in between words: i.e:
this-is-four-words and not one . I'm not even sure that is proper grammar or writing but it was in this file and it certainly threw off my count.
I would like to store some strings in a simple .txt file and then read them, but when I want to encode them using Base64 it doesn't work anymore: it writes well but the reading doesn't work. ^^
The write method:
private void write() throws IOException {
String fileName = "/mnt/sdcard/test.txt";
File myFile = new File(fileName);
BufferedWriter bW = new BufferedWriter(new FileWriter(myFile, true));
// Write the string to the file
String test = "http://google.fr";
test = Base64.encodeToString(test.getBytes(), Base64.DEFAULT);
bW.write("here it comes");
bW.write(";");
bW.write(test);
bW.write(";");
bW.write("done");
bW.write("\r\n");
// save and close
bW.flush();
bW.close();
}
The read method :
private void read() throws IOException {
String fileName = "/mnt/sdcard/test.txt";
File myFile = new File(fileName);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader inBuff = new BufferedReader(new InputStreamReader(fIn));
String line = inBuff.readLine();
int i = 0;
ArrayList<List<String>> matrice_full = new ArrayList<List<String>>();
while (line != null) {
matrice_full.add(new ArrayList<String>());
String[] tokens = line.split(";");
String decode = tokens[1];
decode = new String(Base64.decode(decode, Base64.DEFAULT));
matrice_full.get(i).add(tokens[0]);
matrice_full.get(i).add(tokens[1]);
matrice_full.get(i).add(tokens[2]);
line = inBuff.readLine();
i++;
}
inBuff.close();
}
Any ideas why?
You have a couple of errors in your code.
First a couple of notes on your code:
When posting here, attaching a SSCCE helps others to debug your code. This is not a SSCEE because it doesn't compile. It lacks several defined variables, so one must guess what you really mean. Also you have pasted close-comment token in your code: */ but there is no one start-comment token.
Catching and just suppressing exceptions (like in catch-block in read method) is really bad idea unless you really know what you're doing. What it does most of the time is hide the potential problems from you. At least write the stacktrace of an exception is a catch block.
Why don't you just debug it, check what exactly outputs to the destination file? You should learn how to do that because that will speed up your development process, especially for larger projects with hard-to-catch problems.
Back to the solution:
Run the program. It throws an exception:
02-01 17:18:58.171: E/AndroidRuntime(24417): Caused by: java.lang.ArrayIndexOutOfBoundsException
caused by line here:
matrice_full.get(i).add(tokens[2]);
inspecting the variable tokens reveals that it has 2 elements, not 3.
So lets open the file generated by the write method. Doing that shows this output:
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
Note line breaking here. This is because the Base64.encodeToString() appends additional newline at the end of the encoded string. To generate a one single line, without extra newlines, add Base64.NO_WRAP as the second parameter like this:
test = Base64.encodeToString(test.getBytes(), Base64.NO_WRAP);
Note here, you must delete file that was created earlier as it has improper line breaking.
Run the code again. It now creates a file with the proper contents:
here it comes;aHR0cDovL2dvb2dsZS5mcg==;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==;done
Printing the output of matrice_full now gives:
[
[here it comes, aHR0cDovL2dvb2dsZS5mcg==, done],
[here it comes, aHR0cDovL2dvb2dsZS5mcg==, done]
]
Note that you're not doing anything with the value in decode variable in your code, hence the second element is the Base64 representation of that value which is read from the file.
I am working on application which will read the text file from the SD card and write its contents to other text file.
The implementation goes like this:
File result = new File("/mnt/sdcard/result.txt");
result .createNewFile();
FileWriter resultFileWriter = new FileWriter(result , true);
File f = new File("/mnt/sdcard/abc.txt");
BufferedReader mainBufferedReader =
new BufferedReader(new FileReader(f));
while((line = mainBufferedReader.readLine() ) != null)
{
lineNo ++
if(lineNo > 50 )
{
resultFileWriter .append(line);
resultFileWriter .append("\n");
resultFileWriter .flush();
}
}
resultFileWriter .close();
resultFileWriter = null;
mainBufferedReader .close();
mainBufferedReader = null;
The above code is working properly , but very few times ( 1 outof 20) it is taking much time do the above operation.
I suspect this is because of slow response from the SD card.
Please suggest me generally when there's chance to slow response from SD card.
or please let me know if there's any changes I need to do in my code.
Thanks.
As far as I remember this video is about such kind of delays:
http://developer.android.com/videos/index.html#v=c4znvD-7VDA
But the idea is to perform I/O operations asynchronously so these delays won't be able to slow down your UI.
Its better to use SQLITE DB. DB read/write is always faster than File I/O.