I've a string object s. I write to it using a bufferedReader.readline(). I've logged out the contents of s and in logcat i can see them, so i know it's not null. I later use s and call String.split on it, but i'm getting a NPE, why, when it's already populated so not null?
thanks.
String cachePath = getCacheDir().getAbsolutePath();
FileReader fr = null;
try {
fr = new FileReader(cachePath + "/dbcache/" + "cacheTextFile.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(fr);
String s = null;
try {
while((s = br.readLine()) != null) {
Log.e(TAG, "s = " + s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HashMap<String, String> hash = new HashMap<String, String>();
Log.e(TAG, "about to call on s"+s.length());
String[] arr = s.split(",");
for(int i = 0; i < arr.length; i=i+2){
String key = arr[i].toString();
hash.put(key, "-1");
Log.e(TAG, "hash key = " + hash.get(key));
}
In the while, you are always overriding the s string..so when you reach the end it will be null
while((s = br.readLine()) != null) {
Log.e(TAG, "s = " + s);
}
Do this instead..
StringBuilder stringBuilder = new StringBuilder();
String currentLine = null;
while((currentLine = br.readLine()) != null)
stringBuilder.append(currentLine + "\n");
Related
I am trying to save this boolean array. When I read the array the string array (parts) says that
parts[0]=true;
,but when I use Boolean.parseBoolean array[0] is still false. Can someone help me and tell me what I am doing wrong. Please and Thank You.
public void writeArraytofile() {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("array.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(Arrays.toString(array));
outputStreamWriter.close();
} catch (IOException e) {
Log.v("MyActivity", e.toString());
}
}
public boolean[] read(){
String result = "";
boolean[] array = new boolean[2];
try {
InputStream inputStream = openFileInput("array.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String tempString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((tempString = bufferedReader.readLine()) != null) {
stringBuilder.append(tempString);
}
inputStream.close();
result = stringBuilder.toString();
String[] parts = result.split(" ");
for (int i = 0; i < array.length; i++){
array[i]=Boolean.parseBoolean(parts[i]);
}
}
} catch (FileNotFoundException e) {
Log.v("MyActivity", "File not found" + e.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
//here you catch and watch the problem
Log.e("MyActivity", "cant parse string: " + result);
}
return array;
}
Arrays.toString() will print brackets and commas, so when you read the string back in and call .split(" "), the first piece will be "[true,". Since that is not just "true", Boolean.parseBoolean() will return false.
recently
I try A.txt file read content.
but if my device have not a.txt , occur FileNotFoundException
so I want if my device have not a.txt, How can i stay to proceed?
String path = "/sdcard/Download";
String textName = "a.txt";
String serverVersion = null;
BufferedReader br = null;
try {
br = BufferedReaderFactory.create(path, textName);
StringBuilder contentGetter = new StringBuilder();
while ((serverVersion = br.readLine()) != null) {
serverVersion = serverVersion.trim().toLowerCase();
contentGetter.append('\n' + serverVersion);
Log.d(TAG, " myServerVersion = " + serverVersion);
break;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
You can simple create a variable before try/catch like
boolean isFileFound = false;
So, at the final of the try you set isFileFound = true
like:
String path = "/sdcard/Download";
String textName = "a.txt";
boolean isFileFound = false;
String serverVersion = null;
BufferedReader br = null;
try {
br = BufferedReaderFactory.create(path, textName);
StringBuilder contentGetter = new StringBuilder();
while ((serverVersion = br.readLine()) != null) {
serverVersion = serverVersion.trim().toLowerCase();
contentGetter.append('\n' + serverVersion);
Log.d(TAG, " myServerVersion = " + serverVersion);
break;
}
isFileFound = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (!isFileFound){ // This is equals to if(isFileFound != null)
//Do some message here, like:
Toast toast = Toast.makeText(context, "File not found", Toast.LENGTH_SHORT).show();
}
It looks like you are already handling the exception. If there is no file your code will continue as planned. After your try/catch blocks, you should check if(serverVersion == null) and if it returns true, you know that the serverVersion was not read from the file.
I have been working on this for a while and I am about to pull my hair out!!
If I use this...
public void readFile() {
BufferedReader buffReader = null;
StringBuilder result = new StringBuilder();
try {
FileInputStream fileIn = openFileInput("VariableStore.txt");
buffReader = new BufferedReader(new InputStreamReader(fileIn));
String line;
while ((line = buffReader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert buffReader != null;
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String resultString = result.toString();
String[] controlString = resultString.split("$");
// String wb = controlString[4];
// String sb = controlString[5];
((Button) this.findViewById(R.id.wakeButton)).setText(resultString);
// ((Button) this.findViewById(R.id.sleepButton)).setText(sb);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
}
The Button.setText works fine with "resultString" or with "result" which is a string I have input formatted as xxx$xxx$xxx$xxx$xxx so when I read it back in with the readFile() I want to use .Split and put it into an array "controlString" and then assign the array elements to my widgets i.e. setText(controlString[0]); but if I so much as even uncomment the lines String wb = controlString[4]; or String sb = controlString[5]; my program crashes. Why wont the array elemts work here?
Here is my writeFile().... (Which works perfectly.
public void writeFile() {
BufferedWriter buffWriter = null;
String wb = ((Button)this.findViewById(R.id.wakeButton)).getText().toString();
String sb = ((Button)this.findViewById(R.id.sleepButton)).getText().toString();
String tb = ((EditText)this.findViewById(R.id.textHoursBetween)).getText().toString();
String ti = ((EditText)this.findViewById(R.id.textIncrementTime)).getText().toString();
String td = ((EditText)this.findViewById(R.id.textIncrementDays)).getText().toString();
String writeString = wb + "$" + sb + "$" + tb + "$" + ti + "$" + td;
try {
FileOutputStream fileOut = openFileOutput("VariableStore.txt", Context.MODE_PRIVATE);
buffWriter = new BufferedWriter(new OutputStreamWriter(fileOut));
try {
buffWriter.write(writeString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
assert buffWriter != null;
buffWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found the problem...
Instead of this:
String[] controlString = resultString.split("$");
I had to use this:
String[] controlString = resultString.split(Pattern.quote("$"));
Can "catch" clause be ignored? I have this code and what I wanna do is to scan all words containing a specific string and store them in String res.
But the code I have now does not iterate through the loop because it stops when the "catch" clause interrupts. Is there a way to ignore catch clause and just let the "try" continue the loop until it reaches the end of file?
String delimiter = " - ";
String[] del;
String res = new String();
if(curEnhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
If you really want it to continue on the inner loop even after an error you could put another try block in there.
String delimiter = " - ";
String[] del;
String res = new String();
if(curEnhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
try {
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
}
catch (Exception e) {
// Error in string processing code (as opposed to IO) - Don't care... Continue
}
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
Another idea is to use more specific Exceptions - not just the general catch all Exception
I thing you must be getting exception inside while, So try this.
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
try{
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
} catch(Exception e){
// Do Something
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
If you get exception it would be handled inside the loop but your loop will continue.
There is nothing in your catch clause. Try to add something like below for while loop(keep it in try block) as well to find out which exception u got:
catch(Exception e)
{
Log.e("Exception here: "+ e.getMessage());
}
I'm trying to read from a text file under /data/data/package_name/files.
This is my code:
private String readTxt(String fileName)
{
String result = "", line;
try
{
File f = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
while((line = br.readLine()) != null)
{
result += line + "\n";
}
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
What am I doing wrong?
You should use the openFileInput Method from your application context. http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
Which will give you a InputStream to your file
Example:
final InputStream is = getApplicationContext().openFileInput(MY_FILENAME_WITHOUT_PATH);
private String getStringFromFile(Context accessClass,String fileName){
String result=null;
FileInputStream fIn;
ContextWrapper accessClassInstance=new ContextWrapper(accessClass);
try {
fIn = accessClassInstance.openFileInput(fileName);
InputSource inputSource=new InputSource(fIn);
InputStream in = inputSource.getInputStream();
if (in != null) {
// prepare the file for reading
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
result = "";
while (( line = buffreader.readLine()) != null) {
result += line;
}
in.close();
Toast.makeText(getApplicationContext(),"File Contents ==> " + result,Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}