簡體   English   中英

Android / java Cant從本地存儲中的.txt文件讀取

[英]Android/java Cant read from .txt file in local storage

所以我在本地存儲中有一個.txt文件,它是一個簡單的文本文件。 文本基本上只是一系列行。

我正在使用下面的代碼嘗試讀取文本文件(在調用此方法之前,我先驗證文件是否存在)。

public static String GetLocalMasterFileStream(String Operation) throws Exception {

//Get the text file
    File file = new File("sdcard/CM3/advices/advice_master.txt");
    if (file.canRead() == true) {System.out.println("-----Determined that file is readable");}

    //Read text from file
    StringBuilder text = new StringBuilder();
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        System.out.println("-----" + line);   //for producing test output
        text.append('\n');

    }
    br.close();
    System.out.print(text.toString());
    return text.toString();

}

代碼在日志中產生

----確定文件是可讀的,但這是唯一輸出,文件數據未寫入日志

我也嘗試在while循環之前插入以下內容以嘗試僅讀取第一行

 line = br.readLine();
 System.out.println("-----" + line);

產生以下輸出:

- - -空值

看看這個getExternalStorage

     File path = Environment.getExternalStorageDirectory();
     File file = new File(path, "textfile.txt");
//text file is copied in sdcard for example

嘗試在文件路徑/sdcard/CM3/advices/advice_master.txt中添加斜杠

 File file = new File("/sdcard/CM3/advices/advice_master.txt");

嘗試這個。 只需將txt文件名作為參數傳遞...

public void readFromFile(String fileName){
    /*
    InputStream ips;
    ips = getClass().getResourceAsStream(fileName);

    //reading
    try{
        InputStreamReader ipsr = new InputStreamReader(ips);
        BufferedReader br = new BufferedReader(ipsr);
        String line;

        while ((line = br.readLine())!=null){
            //reading goes here ;)
        }
        br.close();
    }
    catch (Exception e){
        System.out.println(e.toString());
    }
   */
// or try this
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
   }


}

讓我完善我的答案。 您可以嘗試另一種方式來讀取advice_master.txt中的所有行,然后看看會發生什么。 它確保可以讀取所有文件內容。

Charset charset = Charset.forName("ISO-8859-1");
try {
  List<String> lines = Files.readAllLines(Paths.get(YOUR_PATH), charset);

  for (String line : lines) {
    System.out.println(line);
  }
} catch (IOException e) {
  System.out.println(e);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM