How to create a file with the data of an InputStream using commands?

0

I have asked this question to be able to solve my doubt or obstacle, which is:

I want to be able to create a file but not empty already created with its data from the command terminal.

Why from the command terminal and not from java with the File and OutputStream class? Because I need to be able to create it from the command terminal, because my application uses Root permissions and what I'm doing is root movements from my application from commands, because I do not know how to do it or I know a way to do it from java code.

My current command only creates an empty file.

String[] command2 = {"su", "-c", "touch", Ruta del archivo};
    try{
    Process proc2 = Runtime.getRuntime().exec(command2);
    Toast.makeText(this, "Si", Toast.LENGTH_LONG).show();

    }catch (IOException e1) {
        // TODO: handle exception
    }

Small information: in my research I found something about the vi command, but draw the conclusion that it's just a text editor of txt files, but I do not know if it has more functions.

If you know any way to achieve my goal, please let me know. Thanks

    
asked by Abraham.P 20.02.2017 в 22:34
source

1 answer

1

Edit: App with root permission

  

WARNING 1: Modifying system files could damage your computer, if you do not know what is being done.

     

WARNING 2: This exists in SO in English: this is the link .

Source of this code: view here

public abstract class ExecuteAsRootBase
{
   public static boolean canRunRootCommands()
   {
      boolean retval = false;
      Process suProcess;

      try
      {
         suProcess = Runtime.getRuntime().exec("su");

         DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
         DataInputStream osRes = new DataInputStream(suProcess.getInputStream());

         if (null != os && null != osRes)
         {
            // Getting the id of the current user to check if this is root
            os.writeBytes("id\n");
            os.flush();

            String currUid = osRes.readLine();
            boolean exitSu = false;
            if (null == currUid)
            {
               retval = false;
               exitSu = false;
               Log.d("ROOT", "Can't get root access or denied by user");
            }
            else if (true == currUid.contains("uid=0"))
            {
               retval = true;
               exitSu = true;
               Log.d("ROOT", "Root access granted");
            }
            else
            {
               retval = false;
               exitSu = true;
               Log.d("ROOT", "Root access rejected: " + currUid);
            }

            if (exitSu)
            {
               os.writeBytes("exit\n");
               os.flush();
            }
         }
      }
      catch (Exception e)
      {
         // Can't get root !
         // Probably broken pipe exception on trying to write to output stream (os) after su failed, meaning that the device is not rooted

         retval = false;
         Log.d("ROOT", "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage());
      }

      return retval;
   }

   public final boolean execute()
   {
      boolean retval = false;

      try
      {
         ArrayList<String> commands = getCommandsToExecute();
         if (null != commands && commands.size() > 0)
         {
            Process suProcess = Runtime.getRuntime().exec("su");

            DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());

            // Execute commands that require root access
            for (String currCommand : commands)
            {
               os.writeBytes(currCommand + "\n");
               os.flush();
            }

            os.writeBytes("exit\n");
            os.flush();

            try
            {
               int suProcessRetval = suProcess.waitFor();
               if (255 != suProcessRetval)
               {
                  // Root access granted
                  retval = true;
               }
               else
               {
                  // Root access denied
                  retval = false;
               }
            }
            catch (Exception ex)
            {
               Log.e("ROOT", "Error executing root action", ex);
            }
         }
      }
      catch (IOException ex)
      {
         Log.w("ROOT", "Can't get root access", ex);
      }
      catch (SecurityException ex)
      {
         Log.w("ROOT", "Can't get root access", ex);
      }
      catch (Exception ex)
      {
         Log.w("ROOT", "Error executing internal operation", ex);
      }

      return retval;
   }
   protected abstract ArrayList<String> getCommandsToExecute();
}

Edit: Code for Android, I had not noticed You can do it perfectly on android. It is explained clearly and in Spanish at developer android .

String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;

try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(string.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}

Code for Desktop Applications In Java you can perfectly create an empty file and add content, create a file from another, or write content in a file that already exists, delete it, etc. Of course, do not try to do anything in a file that exists in a directory that you do not have permission to access, because of course it will not be possible.

Example of creating a file that does not exist and adding content. This example will look for a file called logfile.txt and if it does not find it, create it in the directory specified in the variable p of the type Path: Taken from the Java doc

import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.io.*;

public class LogFileTest {

  public static void main(String[] args) {

    // Convert the string to a
    // byte array.
    String s = "Hello World! ";
    byte data[] = s.getBytes();
    Path p = Paths.get("./logfile.txt");

    try (OutputStream out = new BufferedOutputStream(
      Files.newOutputStream(p, CREATE, APPEND))) {
      out.write(data, 0, data.length);
    } catch (IOException x) {
      System.err.println(x);
    }
  }
}
    
answered by 20.02.2017 / 22:51
source