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("$"));
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.
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 am trying to make the computer read a text file full of words and add it to an ArrayList. I made it work on a regular Java application, but can't get it to work on Android. Can someone help me out?
try {
FileInputStream textfl = (FileInputStream) getAssets().open("test.txt");
DataInputStream is = new DataInputStream(textfl);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String strLine;
while ((strLine = r.readLine()) != null) {
tots.add(strLine); //tots is the array list
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I keep getting a error. The text file is 587kb, so could that be a problem?
try this.
private static String readTextFile(String fileName)
{
BufferedReader in = null;
try
{
in = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
String line;
final StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
{
buffer.append(line).append(System.getProperty("line.separator"));
}
return buffer.toString();
}
catch (final IOException e)
{
return "";
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
// ignore //
}
}
}
I am using the code below to read the the txt files from my SD card, but how can I display it as Text View?
try{
File f = new File(Environment.getExternalStorageDirectory()+"/filename.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
This should do it :
public void displayOutput()
{
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"/TextFile.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),"File not found!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
TextView output=(TextView) findViewById(R.id.output);
// Assuming that 'output' is the id of your TextView
output.setText(text);
}
LinearLayout myVerticalLinearLayout = (LinearLayout) findViewById(R.id.myLinearLayout);
TextView text = new TextView(getApplicationContext());
text.setText(readString);
myVerticalLinearLayout.addView(text);
That should add vertical text views in a linear layout you should have created before.
public String readText(){
//this is your text
StringBuilder text = new StringBuilder();
try{
File f = new File(Environment.getExternalStorageDirectory()+"/filename.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = "";
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
text.append(readString + "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return text.toString();
}
...
TextView tv=findViewById(.....);
tv.setText(readText());
public class ReadFileActivity extends Activity {
/** Called when the activity is first created. */
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text=(TextView)findViewById(R.id.textview);
text.setText(readTxt());
}
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.aaa);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
}