【发布时间】:2015-12-30 15:50:42
【问题描述】:
好的,我正在尝试从服务器检索 .txt 文件,将其写入本地文件,然后稍后再调用它。
我注意到我在本地复制文件后无法读回文件
起初我认为我的回读代码有问题,因为当我在 wordpad 或 wordpad++ 中打开文件时,就我可以告诉文件的内容而言,内容存在并正确写入。
但是经过大量测试后,我确定回读代码没有任何明显错误。
所以我添加了一个测试,我在执行复制的代码中添加了一些静态写入:
bw.write("这是测试" + "\r\n");
bw.write("我的第一行!" + "\r\n");
bw.write("我的第二行");
bw.write("继续...P" + "\r\n");
现在,当我运行它时,所有内容都正确写入文件(或看起来),但在回读期间,仅读取上面的静态写入。
尽管我可以直观地看到文件中的内容,但从基于 Web 的文件中复制的内容(尽管存在)永远不会读回。
任何帮助将不胜感激
这是我用来读取和复制文件的代码 ** 这是我在网上阅读的文件 CrewAdviceMasterControlURL = http://lialpa.org/CM3/CrewAdvices/advice_master.txt
public static String GetMasterFileStream(String Operation) throws Exception {
StringBuilder sb = new StringBuilder();
BufferedWriter bw = null;
String inputLine = null;
URL AdviceMasterControl = new URL(CrewAdviceMasterControlURL);
File outfile = new File("sdcard/CM3/advices/advice_master.txt");
if(!outfile .exists()){
outfile .createNewFile();
}
FileWriter fileWriter = new FileWriter(outfile);
bw = new BufferedWriter(fileWriter);
BufferedReader in = new BufferedReader(new InputStreamReader(AdviceMasterControl.openStream()));
System.out.println("Creating the master");
bw.write("This is the test" + "\r\n");
bw.write("My first line!" + "\r\n");
bw.write("My second line ");
bw.write("keeps going on...P" + "\r\n");
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine); //for producing test output
sb.append((inputLine + "\r\n"));
bw.write(String.valueOf(inputLine) + "\r\n");
}
in.close();
bw.close();
return sb.toString();
}
这是我用来读回的代码
public static String GetLocalMasterFileStream(String Operation) throws Exception {
String FullPath = "/sdcard/CM3/advices/advice_master.txt";
System.out.println("path is " + FullPath);
File file = new File(FullPath);
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;
line = br.readLine();
System.out.println("-----" + line);
while ((line = br.readLine()) != null) {
text.append(line);
System.out.println("-----" + line); //for producing test output
text.append('\n');
}
br.close();
return text.toString();
}
【问题讨论】:
-
你看懂你写的了吗?因为我没有。
-
ok 编辑了一些格式
-
我只能看到你写的东西(阅读你的代码也很明显)。但是我看不到您阅读的内容(应该是相同的)。但是,如果你得到你所放的......那么它就起作用了。如果是这样,我无法理解这篇文章的含义。
-
从网络上的.txt文件中读取的内容被正确读取,因为我可以将其写入日志。但是由于某种原因,当我将同一行文本写入 .txt 文件时,我无法使用代码重新读取它。但是,如果我打开记事本,它就在文件中。我怀疑它的某种格式问题
-
也许只是编码不同。它发生在 Windows 和 Unix 之间。
标签: java android io bufferedreader bufferedwriter