Reputation: 2192
I have problem. I create with my code text file called test.txt then I get text from system file with cat command and this text put to my test.txt, but I don't know how to read the text from this file. I need read text from this file and then save it to my SharedPreferences. Here is code:
try {
FileOutputStream fos = new FileOutputStream("/sdcard/test.txt");
DataOutputStream dos = new DataOutputStream(fos);
dos.flush();
dos.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Process a;
try {
a = Runtime.getRuntime().exec("su");
DataOutputStream aaa = new DataOutputStream(a.getOutputStream());
aaa.writeBytes("cat /proc/sys/sad/asdsad > /sdcard/test.txt\n");
aaa.writeBytes("exit\n");
aaa.flush();
try {
a.waitFor();
if (a.exitValue() != 255) {
// TODO Code to run on success
toastMessage("root");
}
else {
// TODO Code to run on unsuccessful
toastMessage("not root");
}
} catch (InterruptedException e) {
// TODO Code to run in interrupted exception
toastMessage("not root");
}
} catch (IOException e) {
// TODO Code to run in input/output exception
toastMessage("not root");
}
Upvotes: 0
Views: 889
Reputation: 74780
You don't need to "copy" file to sdcard in order to read it.
And anyway, using "cat" for copying is not what you want in application. As you loose all control over the operation; error detection and handling becomes much harder.
Just use FileReader
and BufferedReader
. An example can be found here. Here is a copy:
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e("TEXT", contents.toString());
All this is very basic stuff. You should consider reading some Java related book or a few articles.
Upvotes: 3