所以我在本地存储中有一个.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);
产生以下输出:
- - - - 空
答案 0 :(得分:0)
File path = Environment.getExternalStorageDirectory();
File file = new File(path, "textfile.txt");
//text file is copied in sdcard for example
答案 1 :(得分:0)
尝试在文件路径/sdcard/CM3/advices/advice_master.txt中添加一个主斜杠
File file = new File("/sdcard/CM3/advices/advice_master.txt");
答案 2 :(得分:0)
试试这个。只需将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
}
}
答案 3 :(得分:0)
让我改进我的答案。你可以尝试另一种方法来读取来自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);
}