How can I process FileNotFoundException ? - android

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.

Related

How to read a .txt file with multiple lines?

I want to save my data in a .txt file. In another activity I want to be able to read the saved data. I want to save multible values each time and put them together on a line, the next values need to be in a new line. I tried \n System.getProperty("line.separator"); System.lineSeparator(); and \n\r to start in a new line but this doesn't seem to work while the data still end up behind each other instead of being on another line.
I use this code to write to the file:
Context context = getApplicationContext();
writedatatofile(context);
protected void writedatatofile(Context context){
try
{
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("data_log.txt", Context.MODE_APPEND));
String data;
if (newstart){
data = "Exersice started \n" + "t.s a.s t.a a.a cnst";
} else {
data = (Integer.toString(time_step)+Integer.toString(new_average_step)+Integer.toString(time_footaid)+Integer.toString(new_average_aid)+Boolean.toString(rhythmconsistent)+"\n");
}
outputStreamWriter.append(data);
outputStreamWriter.close();
Toast.makeText(this, "Data has been written to File", Toast.LENGTH_SHORT).show();
}
catch(IOException e) {
e.printStackTrace();
}
}
and this code to read the file:
Context context = getApplicationContext();
String fileData = readFromFile(context, fileName);
TextView datalog = findViewById(R.id.datalog);
datalog.setText(fileData);
private String readFromFile(Context context, String fileName){
String ret = " ";
try {
InputStream inputStream = context.openFileInput(fileName);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
Toast.makeText(this, "Data received", Toast.LENGTH_SHORT).show();
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
} else {
Toast.makeText(this, "No data received", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e){
Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
} catch (IOException e){
Toast.makeText(this, "Can not read file", Toast.LENGTH_SHORT).show();
}
return ret;
}
As mentioned "\n" doesn't solve the problem but is also doesn't show up in my dataas \n. So it is not stored as a normal String.
When you write the file:
BufferedWriter writer = new BufferedWriter(outputStreamWriter);
writer.write(data);
writer.newLine(); // <-- this is the magic
writer.close();
You can read the data from .txt file using below code.
File exportDir = new File(Environment.getExternalStorageDirectory(), File.separator + "bluetooth/abc.txt");
if (exportDir.exists()) {
FileReader file = null;
try {
file = new FileReader(exportDir);
BufferedReader buffer = new BufferedReader(file);
String line = "";
int iteration = 0;
while ((line = buffer.readLine()) != null) { //read next line
if (iteration == 0) { //Skip the 1st position(header)
iteration++;
continue;
}
StringBuilder sb = new StringBuilder();
String[] str = line.split(",");
//get the single data from column
String text1 = str[1].replace("\"", "");
String text2 = str[2].replace("\"", "");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Android Studio - Why does a string array cause my program to stop?

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("$"));

Saving int values to SD and read them

I have succesfully saved int values to sd but cant read. It always gives numberformat information. I made all logics, but cant find why it gives error.
Here is my code ;
this my constant
private final static String EXTERNAL_FILES_DIR = "ARDROID";
private final static String FILE_NAME = "turkcell.txt";
private boolean isThereAnySavedFile = false;
when this method called, it tries to open file, if file does not exist, create the file
public void anySavedDataInSD() {
String textFromSD = String.valueOf(read());
if (isThereAnySavedFile) {
int numberOfSendedSMS = Integer.parseInt(textFromSD.toString());
numberOfSendedSMS++;
writeToSD(String.valueOf(numberOfSendedSMS));
} else {
int first=60;
String g = String.valueOf(first);
writeToSD(g);
}
}
this method for writing
private void write(File file, String msg) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(msg.getBytes());
Logger.info("oldu bu kez");
} catch (IOException e) {
Logger.info("oldu bu kez2" + e);
} finally {
Logger.info("oldu bu kez3");
try {
if (outputStream != null)
outputStream.close();
} catch (IOException exception) {
}
}
}
this methof for reading
public StringBuilder read() {
StringBuilder textBuilder = new StringBuilder();
BufferedReader reader = null;
try {
File externalFilesDir = getExternalFilesDir(EXTERNAL_FILES_DIR);
File file = new File(externalFilesDir, FILE_NAME);
Logger.info("oldu2");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
isThereAnySavedFile = true;
} catch (FileNotFoundException e) {
Logger.info("oldu3");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return textBuilder;
}

Android - Ignoring Catch Clause?

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());
}

String still null after reading file to it

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");

Categories

Resources