2011-12-08 5 views
0

문제가 있습니다. test.txt라는 코드 텍스트 파일을 작성한 다음 cat 명령으로이 파일을 시스템 파일에서 가져 와서이 텍스트를 my test.txt에 넣습니다. 그러나이 파일에서 텍스트를 읽는 방법을 모르겠습니다. 이 파일의 텍스트를 읽고 SharedPreferences에 저장해야합니다. 당신은 "복사"파일을 읽기 위해 sdcard에 할 필요가 없습니다sdcard 파일에서 텍스트를 읽는 방법은 무엇입니까?

try { 
      FileOutputStream fos = new FileOutputStream("/sdcard/test.txt"); 
      DataOutputStream dos = new DataOutputStream(fos); 
      dos.flush(); 
      dos.close(); 
     } catch (FileNotFoundException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

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

      DataOutputStream aaa = new DataOutputStream(a.getOutputStream()); 
      aaa.writeBytes("cat /proc/sys/sad/asdsad > /sdcard/test.txt\n"); 
      aaa.writeBytes("exit\n"); 
      aaa.flush(); 
      try { 
       a.waitFor(); 
       if (a.exitValue() != 255) { 
        // TODO Code to run on success 
        toastMessage("root"); 
        } 
       else { 
        // TODO Code to run on unsuccessful    
        toastMessage("not root"); 
        } 
      } catch (InterruptedException e) { 
       // TODO Code to run in interrupted exception  
       toastMessage("not root"); 
       } 
     } catch (IOException e) { 
      // TODO Code to run in input/output exception 
      toastMessage("not root"); 
      } 

답변

3

: 여기 는 코드입니다.

어쨌든 "cat"을 복사에 사용하면 응용 프로그램에서 원하는 것이 아닙니다. 조작에 대한 모든 제어를 잃어 버릴 때; 오류 감지 및 처리가 훨씬 더 어려워집니다.

FileReaderBufferedReader 만 사용하십시오. 예는 here입니다. 사본은 다음과 같습니다.

File file = new File("test.txt"); 
StringBuffer contents = new StringBuffer(); 
BufferedReader reader = null; 

try { 
    reader = new BufferedReader(new FileReader(file)); 
    String text = null; 

    // repeat until all lines is read 
    while ((text = reader.readLine()) != null) { 
     contents.append(text) 
      .append(System.getProperty(
       "line.separator")); 
    } 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    try { 
     if (reader != null) { 
      reader.close(); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
}   

Log.e("TEXT", contents.toString()); 

이 모든 것이 매우 기본적인 것입니다. Java 관련 서적이나 몇 가지 기사를 읽는 것을 고려해야합니다.

+0

예,이 코드를 잘 알고 있고 기본 프로그래밍을 잘 이해하고 있지만 최근 Android에서 프로그래밍을 시작하여 Java의 모든 명령을 모르는 상태입니다. 내 문제는 공유 환경 설정에 cat 명령을 사용하여 시스템 파일에서 가져온 텍스트를 저장하는 방법을 모른다는 것입니다. 첫 번째 더 쉬운 방법은 시스템 파일의 텍스트를 내 SharedPreferences에 직접 저장하는 것이지만 어떻게 만들지는 모른다. 또는 cat을 사용하여 일부 파일 가져 오기 텍스트를 만들고이 파일에 텍스트를 넣은 다음 생성 된 파일의 텍스트를 SharedPreferences에 넣습니다. – Adam

관련 문제