How to write entire Logcat in to sdcard? - android

I need to write entire Logcat in to sdcard not the filtered Logcat. So I tried doing this way
String[] cmd ={"/system/bin/logcat " +"-f"+" /sdcard/d.txt"};
Log.d("NTK","cmd string"+cmd);
Runtime run = Runtime.getRuntime();
Process pr;
try {
pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null) {
System.out.println(line);
Log.i(NTL, "lines"+line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have given all permissions in manifest file too.
Not able to write logcat in to sdcard.

You can have this Tutorial for Reading the Logs. And for writing the logs in the file you can simply use FileWriter give path of the file with file name.
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
File gpslogfile = new File(root, "log.txt");
FileWriter gpswriter = new FileWriter(gpslogfile, true);
BufferedWriter out = new BufferedWriter(gpswriter);
out.append(DataToWrite);
out.close();
}
} catch (IOException e) {
Log.d("Log: ", "Could not write file " + e.getMessage());
}

Related

Can't create file in the internal storage

i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.

Storing a file to internal storage and reading it

What I am trying to do is store a JSON file as a string in internal storage to access it later. The reasoning behind this is to not have to access the server on every request, as this data is constant. Once it is stored once, it doesn't have to be retrieved again unless there is some sort of update. File storage isn't something I've done before, and I was hoping someone could give me a hand. My current code is throwing a null pointer exception at this line:
File file = new File(getFilesDir(), fileName);
My code:
protected String doInBackground(String[] runeId) {
String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/rune/" + runeId[0] + "?api_key=" + api_key;
JSONParser jsonParser = new JSONParser();
JSONObject runeInfo = jsonParser.getJSONFromUrl(url);
String jsonString = runeInfo.toString();
String fileName = "runeInfo";
File file = new File(getFilesDir(), fileName);
String readJson = null;
if(!runesCached) {
Log.d("Cache", "Caching File");
try {
FileOutputStream os = new FileOutputStream(file);
os.write(jsonString.getBytes());
os.close();
Log.d("Cache", "Cache Complete");
runesCached = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name = null;
try {
FileInputStream fis;
File storedRuneInfo = new File(getFilesDir(), fileName);
fis = new FileInputStream(storedRuneInfo);
fis.read(readJson.getBytes());
JSONObject storedJson = new JSONObject(readJson);
try {
name = storedJson.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
}
Try this, instead:
File file = new File(getFilesDir().toString(), fileName);
getFilesDir() returns a File, not a String, which the File class constructor takes as a parameter.
getFilesDir()toString() should return something like /data/data/com.your.app/
EDIT:
This gives the same error. How about:
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter(getFilesDir() + "/" + "filename");
out = new BufferedWriter(fstream);
out.write(jsonString.getBytes());
out.close();
} catch (Exception e){}

Write file to sdcard in android

I want to create a file on sdcard. Here I can create file and read/write it to the application, but what I want here is, the file should be saved on specific folder of sdcard. How can I do that using FileOutputStream?
// create file
public void createfile(String name)
{
try
{
new FileOutputStream(filename, true).close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// write to file
public void appendToFile(String dataAppend, String nameOfFile) throws IOException
{
fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
fosAppend.write(dataAppend.getBytes());
fosAppend.write(System.getProperty("line.separator").getBytes());
fosAppend.flush();
fosAppend.close();
}
Here's an example from my code:
try {
String filename = "abc.txt";
File myFile = new File(Environment
.getExternalStorageDirectory(), filename);
if (!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = string.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
And don't forget the:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try like this,
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
try {
File file = new File(newFolder, "MyTest" + ".txt");
file.createNewFile();
} catch (Exception ex) {
System.out.println("ex: " + ex);
}
} catch (Exception e) {
System.out.println("e: " + e);
}
It's pretty easy to create folder and write file on sd card in android
Code snippet
String ext_storage_state = Environment.getExternalStorageState();
File mediaStorage = new File(Environment.getExternalStorageDirectory()
+ "/Folder name");
if (ext_storage_state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
if (!mediaStorage.exists()) {
mediaStorage.mkdirs();
}
//write file writing code..
try {
FileOutputStream fos=new FileOutputStream(file name);
try {
fos.write(filename.toByteArray());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//Toast message sd card not found..
}
Note: 'getExternalStorageDirectory()'
actually gives you a path to /storage/emulated/0 and not the actual sdcard
'String path = Syst.envr("SECONDARY_STORAGE");' gives you a path to the sd card

How to write to a textfile in one Activity & read that file in another Activity?

I am able to write and then read a text file in the SAME activity, but I am unable to read a text file after writing to it from another Activity.
Ex: Activity A creates and writes to a text file. Activity B reads that text file.
I use this code to write to the text file in Activity A:
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try
{
fos = openFileOutput("user_info.txt", Context.MODE_WORLD_WRITEABLE);
osw = new OutputStreamWriter(fos);
osw.write("text here");
osw.close();
fos.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And then I use this code to try and read the same text file created by Activity A, but I get a FileNotFoundException:
try
{
FileInputStream fis = openFileInput("user_info.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader buff = new BufferedReader(isr);
String line;
while((line = buff.readLine()) != null)
{
Toast.makeText(this, line, Toast.LENGTH_LONG).show();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Does anyone know why I am getting the FileNotFoundException?
Is it a path issue?
Don't really know how is built your application, but, the error you get does seem like a path issue, are you sure both Activities are in the same folder ?
If not, you'll need to set either an abolute path (like : "/home/user/text.txt") for the text file or a relative path (like : "../text.txt").
If you're not sure, try to print the current path for the Activity using some command like
new File(".").getAbsolutePath();
And, although I can't say I'm expert with Android, are you sure you need the Context.MODE_WORLD_WRITEABLE for your file ? If no other application than yours is reading or writing from/to it, it should not be necessary, right ?
it is surealy a path issue.
you can write like this
fpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory";
File custdir=new File(fpath);
if(!custdir.exists())
{
custdir.mkdirs();
}
File savedir=new File(custdir.getAbsolutePath());
File file = new File(savedir, filename);
if(file.exists())
{
file.delete();
}
FileOutputStream fos;
byte[] data = texttosave.getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
Toast.makeText(getBaseContext(), "File Saved", Toast.LENGTH_LONG).show();
finish();
} catch (FileNotFoundException e) {
Toast.makeText(getBaseContext(), "Error File Not Found", Toast.LENGTH_LONG).show();
Log.e("fnf", ""+e.getMessage());
// handle exception
} catch (IOException e) {
// handle exception
Toast.makeText(getBaseContext(), "Error IO Exception", Toast.LENGTH_LONG).show();
}
and you can read like
String locatefile=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory"+"/filename";
try {
br=new BufferedReader(new FileReader(locatefile));
while((text=br.readLine())!=null)
{
body.append(text);
body.append("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

read text file from phone memory in android

I just wanna create a text file into phone memory and have to read its content to display.Now i created a text file.But its not present in the path data/data/package-name/file name.txt & it didn't display the content on emulator.
My code is..
public class PhonememAct extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=(TextView)findViewById(R.id.tv);
FileOutputStream fos = null;
try {
fos = openFileOutput("Test.txt", Context.MODE_PRIVATE);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fos.write("Hai..".getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = openFileInput("Test.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int c;
try {
while((c=fis.read())!=-1)
{
tv.setText(c);
setContentView(tv);
//k += (char)c;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks in adv.
You don't need to use input/output streams if you are simply trying to write/read text.
Use FileWriter to write text to a file and BufferedReader to read text from a file - it's much simpler. This works perfectly...
try {
File myDir = new File(getFilesDir().getAbsolutePath());
String s = "";
FileWriter fw = new FileWriter(myDir + "/Test.txt");
fw.write("Hello World");
fw.close();
BufferedReader br = new BufferedReader(new FileReader(myDir + "/Test.txt"));
s = br.readLine();
// Set TextView text here using tv.setText(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
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) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
//To read file from internal phone memory
//get your application context:
Context context = getApplicationContext();
filePath = context.getFilesDir().getAbsolutePath();
File file = new File(filePath, fileName);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
return text.toString(); //the output text from file.
This may not be an answer to your question.
I think, you need to use the try-catch correctly.
Imagine openFileInput() call fails, and next you are calling fos.write() and fos.close() on a null object.
Same thing is seen later in fis.read() and fis.close().
You need to include openFileInput(), fos.write() and fos.close() in one single try-catch block. Similar change is required for 'fis' as well.
Try this first!
You could try it with a stream.
public static void persistAll(Context ctx, List<myObject> myObjects) {
// save data to file
FileOutputStream out = null;
try {
out = ctx.openFileOutput("file.obj",
Context.MODE_PRIVATE);
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(myObjects);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is working fine for me like this. Saving as text shouldn't be that different, but I don't have a Java IDE to test here at work.
Hope this helps!

Categories

Resources