Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

linux - Executing a Process in Android to read a file

I need to read the content of a file using a Linux Shell Command executed using Java in Android. What command do I need to execute in order to read all the text in the file and save in a String object?

Note that I can't use the simple Java I/O functions! The file that I need to read is in the device's system directory.

   String command= "";
   String file_path = "misc/file.txt";
   StringBuffer output = new StringBuffer();

      Process p;
      try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";     
        while ((line = reader.readLine())!= null) {
          output.append(line + "
");
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
      String response = output.toString();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
File f=new File("path");
FileInputStream fin=new FileInputStream(f);
byte array[]=new byte[fin.avaialable()];
fin.read(array);
String string=new String(array);

is enough.Why don't you follow simple solutions?

Update

/**
 * Execute a command in a shell
 * 
 * @param command
 *            command to execute
 * @return the return of the command
 */
public String exec(String command) {
    String retour = "";
    try {
        Runtime runtime = Runtime.getRuntime();

        Process p = runtime.exec(command);

        java.io.BufferedReader standardIn = new java.io.BufferedReader(
                new java.io.InputStreamReader(p.getInputStream()));
        java.io.BufferedReader errorIn = new java.io.BufferedReader(
                new java.io.InputStreamReader(p.getErrorStream()));
        String line = "";
        while ((line = standardIn.readLine()) != null) {
            retour += line + "
";
        }
        while ((line = errorIn.readLine()) != null) {
            retour += line + "
";
        }
    } catch (java.io.IOException e) {
        e.printStackTrace();
    }

    return retour;
}

Invoke it as exec("cat misc/file.txt");


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...