I have tried many solutions to read files but no one were working.
I need a method to read a system file and show the text in a toast or in a dialog.
Of course my app has root permission.
I have to show the content of "eoc_status" in a toast after a checkbox click.
For example;
Runtime.getRuntime().exec("/sys/kernel/abb-chargalg/eoc_status").getInputStream();
I need to open text files.
Assuming you do have read-access to eoc_status
You are going to want to read it, not exec it. ie use cat or use a FileReader:
Then you will want to do something (put it in your toast) with the returned InputStream.
For example:
BufferedReader buffered_reader=null;
try
{
//InputStream istream = Runtime.getRuntime().exec("cat /sys/kernel/abb-chargalg/eoc_status").getInputStream();
//InputStreamReader istream_reader = new InputStreamReader(istream);
//buffered_reader = new BufferedReader(istream_reader);
buffered_reader = new BufferedReader(new FileReader("/sys/kernel/abb-chargalg/eoc_status"));
String line;
while ((line = buffered_reader.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e)
{
// TODO
e.printStackTrace();
}
finally
{
try
{
if (buffered_reader != null)
buffered_reader.close();
}
catch (IOException ex)
{
// TODO
ex.printStackTrace();
}
}
Related
After reading a file, I'm trying to delete it, but the following error appears:
java.io.IOException: Unable to delete file test.zip at
org.apache.commons.io.FileUtils.forceDelete (FileUtils.java:1390) at
org.apache.commons.io.FileUtils.cleanDirectory (FileUtils.java:1044)
at org.apache.commons.io.FileUtils.deleteDirectory
(FileUtils.java:977)
Here is my code. I've been careful to close the InputStream in the finally clause and only then call the method that deletes the file, but even then I can only delete it when I stop the program.
InputStream is = null;
try {
is = new URL(filePath).openStream(); // filePath is a string containing the path to the file like http://test.com/file.zip
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
String xml = sb.toString(); // this code is working, the result of the "xml" variable is as expected
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
removeFileAndFolder(absolutePath);
}
private void removeFileAndFolder(String absolutePath) {
new Thread(new Runnable() {
#Override
public void run() {
try {
String folder = getFolder(absolutePath); // this method just get the path to the folder, because I want to delete the entire folder, but the error occurs when deleting the file
FileUtils.deleteDirectory(new File(folder));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
After some tests I discovered that I can manually delete the file just before the line "is = new URL (filePath) .openStream ();". After it, and even after the line "is.close ();" I can not delete the file manually unless I stop the program.
I got it. I was opening the file by the url (is = new URL(filePath).openStream();), and trying to delete it by absolute path. I changed it to "is = new FileInputStream(absoluteFilePath);" and it works!
My code is creating a file to save data into, but it's also overwriting the previous data that was saved previously under that same file name. How do I modify my code in order to save the new data without affecting the old one? I want my data to be saved with a line that separates the old one. Here is my code part of saving:
public void buttonSave(View view) {
File file = new File(path + "/Data.txt");
String[] saveText = String.valueOf(editText.getText()).split(System.getProperty("line.separator"));
editText.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Save(file, saveText);
}
You could try reading the data from your file into a String and then add new text to the string. After that save the file with the newly added info and you're done. Here's a sample on how to read the file:
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Simple Question I know - but my android app simply can´t find my CSV file. I´ve placed the file here:
and access it with this code:
public void getFragenfromCSV(){
AssetManager a = getAssets();
BufferedReader reader = null;
try {
InputStream is = a.open("fragenbronze.csv");
reader = new BufferedReader(new InputStreamReader(s));
} catch (IOException e) {
System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
e.printStackTrace();
}
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
System.out.println(RowData[0]);
}
}
catch (IOException ex) {
// handle exception
}
}
On running the app I always get the IOException from the catch part.
you have to place it in
src/main/assets
never put something you want to keep in build/ as this get's removed with clean
Project Structure with assets folder
You are going inside build but actually you have to go inside src/main/assets.
When i use command prompt on PC and connect device and run abd to execute below command
abd logcat -d > abc.txt
It returns a big file "abc.txt" with all the entries of logcat of all apps. But when I run the same command in an app on android to store it on SD card by making a file it just stores the recent logcat entries and only logs for this app and not even previous logs. Can somebody tell me why is this happening I have also given permission to READ_LOGS
Here is the android code
String fullName = "appLog.txt";
File file = new File (Environment.getExternalStorageDirectory(), fullName);
//clears a file
if(file.exists()){
file.delete();
}
//write log to file
try {
String command = String.format("logcat -d");
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder result = new StringBuilder();
String currentLine = null;
while ((currentLine = reader.readLine()) != null) {
result.append(currentLine);
result.append("\n");
}
FileWriter out = new FileWriter(file);
out.write(result.toString());
out.close();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
//clear the log
try {
Runtime.getRuntime().exec("logcat -c");
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
public void appendLog(String text)
{
File logFile = new File("/sdcard/log.txt");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And use the method to log from anywhere you need.
appendLog("your message" + anyvalueyouwanttolog );
In Jelly Bean this has changed. App can read only it's own logs and don't need anymore READ_LOGS permission.
As alternative you can use log4j for android. You can use file appender to store all the logs in some file and also LogCatAppender to print logs to logcat, so you can watch logs while developement within eclipse for e.g.
For catching all uncaught exceptions you can create class that implements UncaughtExceptionHandler and then use it with Thread.setDefaultUncaughtExceptionHandler(). This is then useful for printing crash reports (stack traces) to your log and/or to separate file.
I am newbie in android development. Today for i was trying to display all my practiced programs of java in my application. I want the application to read the data written in .txt file.
In which folder should I store all my programs? They are more than 100.
I want to display the content of program 2 when I clicked the 2 on the list view or any other
Can we store the text files in database? If so how can I access them ? How can I read them?
Any basic ideas how can I solve this?
You can kept text file in raw / assets folder.
To read them just use this code.
From Assets:
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("YourTextFile.txt")));
From Raw:
InputStream inputStream = context.getResources().openRawResource(R.id.yourresoureid);
InputStreamReader inputreader = new InputStreamReader(inputStream)
as you are a java programmer no need to tell how to read data from InputStream, if your really want then tell me I will post the rest of the code.
Saving that huge amount of data in data base is not a good idea.
Example to read data from InputStream
BufferedInputStream bis=new BufferedInputStream(inputstream);
ByteArrayBuffer baf=new ByteArrayBuffer(1000);
while((k=bis.read())!=-1)
{
baf.append((byte)k);
}
String results=new String(baf.toByteArray());
Start with something easy and work up to the database option.
Yes, the answer would be quite long, and I think a tutorial on SQLite would be a place to start on this.
2,1. Try putting your text files in the assets folder and reading them like this. This code reads a file, and dumps it line by line into the log.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
AssetManager assetManager = getAssets();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
assetManager.open("hi.txt")));
// InputStream inputStream = assetManager.open("hi.txt");
// BufferedReader br = new BufferedReader(
// new InputStreamReader(inputStream));
String lineIn;
while ((lineIn = br.readLine()) != null) {
Log.d("ReadTheDamnFile", lineIn);
}
assetManager.close();
} catch (IOException e) {
}
}
try this its work fine :)
try
{
if(poslist==0)
{
in = this.getAssets().open("file1.txt");
iv.setBackgroundResource(R.drawable.fileimage1);
}
}
catch (IOException e)
{
e.printStackTrace();
}
try {
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line="";
String s ="";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
while (line != null)
{
s = s + line;
s =s+"\n";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
tv.setText(""+s);
}
public void onClick(View v){
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (line != null){
tv.setText(line);
} else {
//you may want to close the file now since there's nothing more to be done here.
}