-2

I want to print the stack (after an error in an exception block, try catch), but I wanna print all in an external file (.txt), file that I can take somewhere in the android folders.

Thanks in advance

manman
  • 4,743
  • 3
  • 30
  • 42

4 Answers4

0

Open/declare a PrintWriter to write to your file and change your catch block to:

catch(Exception e) {
    e.printStackTrace(your_print_writer);
}
Deepesh Choudhary
  • 660
  • 1
  • 8
  • 17
0

Well, that could be a problem, but it's totally doable:

try {
    badMethod();
} catch(SomeException e) {
    try (FileWriter writer = new FileWriter("file.txt")) {
        e.printStackTrace(writer);
    } catch(IOException ioexception) {
        // do something here
    }
}
Rafael Guerreiro
  • 196
  • 3
  • 14
0

There are a lot of ways to do that, but maybe the easiest is to redirect System.err to your desired file an then simply call Exception.printStackTrace();

To redirect standard error output:

PrintStream ps = new PrintStream("./errors.txt");
System.setErr(ps);

and then...

catch(Exception e) {
    e.printStackTrace();
}
LuisGP
  • 431
  • 3
  • 13
  • You can specify any file path you wish. In this case, the file will be in the current directory, that typically is the one from which your app is running. You can see it with any text viewer. In android I use ES File Explorer suite. – LuisGP May 08 '17 at 20:05
  • Did I resolve your question? If yes, please, consider mark as the answer. – LuisGP May 19 '17 at 11:01
-1

You can do it this way :

try{
    // action
} catch (IOException e) {
    PrintWriter writer = new PrintWriter("stacktrace.txt");
    e.printStackTrace(writer);
    writer.close();
}
Omar Aflak
  • 2,918
  • 21
  • 39