B4J Code Snippet Redirect the output to a file

Discussion in 'B4J Code Snippets' started by Erel, Mar 28, 2016.

  1. Erel

    Erel Administrator Staff Member Licensed User

    Name: RedirectOutput

    Description: This sub will redirect the program output to a file.

    Code:
    Sub RedirectOutput (Dir As String, FileName As String)
       
    #if RELEASE
       Dim out As OutputStream = File.OpenOutput(Dir, FileName, False) 'Set to True to append the logs
       Dim ps As JavaObject
       ps.InitializeNewInstance("java.io.PrintStream", Array(out, True, "utf8"))
       Dim jo As JavaObject
       jo.InitializeStatic("java.lang.System")
       jo.RunMethod("setOut", Array(ps))
       jo.RunMethod("setErr", Array(ps))
       
    #end if
    End Sub
    Usage:
    Code:
    RedirectOutput(File.DirApp, "logs.txt")
    If this app will be installed with an installer then you should not use File.DirApp as it will be read-only.
     
  2. jinyistudio

    jinyistudio Active Member Licensed User

    Hi

    How do i redirect to Standard output(Screen) again when i redirect it to file ?
     
  3. Erel

    Erel Administrator Staff Member Licensed User

    Initialize ps with this code:
    Code:
    Dim fd As JavaObject
    fd.InitializeStatic(
    "java.io.FileDescriptor")
    Dim jout As JavaObject
    jout.InitializeNewInstance(
    "java.io.FileOutputStream"Array(fd.GetField("out")))
    ps.InitializeNewInstance(
    "java.io.PrintStream"Array(jout, True"utf8"))
     
    Jmu5667, DonManfred and jinyistudio like this.
  4. Mashiane

    Mashiane Expert Licensed User

    I'm getting... failed to initialize logger
     
  5. Erel

    Erel Administrator Staff Member Licensed User

    Can you post the full error message from the logs?
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice