简体   繁体   English

使用BufferReader和BufferWriter写入文件时,文件创建为空

[英]Files are created empty when using BufferReader and BufferWriter to write a file

I'm trying to load a JSON from webservice and write it to a file using the following code: 我正在尝试从Web服务加载JSON,并使用以下代码将其写入文件:

File cacheDir = new File(context.getCacheDir(), "texts");
cacheDir.mkdirs();
File cacheFile = new File(cacheDir, "" + articleId);
try {
    if (!cacheFile.exists()) {
        try {
            HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
            try {
                InputStream in = c.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                // this approach fails
                /*
                BufferedWriter writer = new BufferedWriter(new FileWriter(cacheFile.getAbsolutePath()));

                String line = null;
                while ((line = reader.readLine()) != null) {
                    writer.write(line);
                    writer.newLine();
                }
                writer.flush();
                reader.close();
                writer.close();
                */

                // this approach works
                Gson g = new Gson();
                Article article = g.fromJson(reader, Article.class);
                String json = g.toJson(article);

                PrintWriter out = new PrintWriter(new FileWriter(cacheFile.getAbsolutePath()));
                out.print(json);

                out.flush();
                out.close();
                reader.close();

            } catch (IOException e) {
                Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
            } finally {
                c.disconnect();
            }
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
        }
    }
}

I've checked with adb shell and Android Monitor file browswer and the files seem to be created: 我检查了adb shell和Android Monitor文件浏览器,发现文件似乎已创建:

在此处输入图片说明

However, when I do cat filename from adata/data/appdir/cache no file content is printed (only command is printed again cat filename ). 但是,当我从adata/data/appdir/cache执行cat filename ,没有文件内容被打印(仅再次打印命令cat filename )。 What is wrong with my approach? 我的方法有什么问题?

You are doing all the operations inside 您正在内部进行所有操作

if (!cacheFile.exists()) {
   //your code here
}

The file.exists() method returns true if a file denoted by the path exists. 如果路径表示的文件存在,则file.exists()方法返回true。 So in effect what you are saying is 'do my operations if the file does not exist' which does not make sense. 因此,实际上,您要说的是“如果文件不存在,请执行我的操作”,这没有任何意义。

Instead you could 相反,你可以

if (!cacheFile.exists()) {
    cacheFile.createNewFile() 
}
//do the rest of your stuff here

Instead of use readLine to read from the InputStream, try with read and a char[] 而不是使用readLine从InputStream read ,请尝试使用readchar[]

if (in != null) {
    StringBuffer stringBuffer = new StringBuffer();
    final char[] charBuffer = new char[8 * 1024];
    reader = new BufferedReader(new InputStreamReader(in), charBuffer.length);
    int read;  
    while ((read = reader.read(charBuffer)) != -1) {
         stringBuffer.append(charBuffer, 0, read);
    }
    PrintWriter out = new PrintWriter(new FileWriter(cacheFile.getAbsolutePath()));
    out.print(stringBuffer.toString());
    out.flush();
    out.close();
    reader.close();
    Gson g = new Gson();
    Article article = g.fromJson(stringBuffer.toString(), Article.class);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 BufferWriter 和 BufferReader 通过 TCP 套接字发送图像 - Send image by TCP Socket using BufferWriter and BufferReader Java BufferWriter未完成文件写入 - Java BufferWriter not completing write of file 使用BufferWriter从多个类写入同一文件 - Write to the same file using BufferWriter from multiple classes 使用 read() 时 BufferReader 卡住 - BufferReader stucks when using read() 使用\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\。 - “\n” not adding new line when saving the string to text using BufferWriter to text file 使用 Files.write 将字符串写入特定创建文件夹的文件中 - Using Files.write to write a string into a file of specefic created folder 当我发送以数据包分隔的文件时,新创建的文件为空 - When I send files separated by packets, the new created file is empty 是否使用由filewriter线程安全初始化的bufferwriter写入文件? - Is writting on file using bufferwriter initialized by filewriter thread safe or not? 使用BufferWriter将存储在数组中的String和Double值写入文件 - Writing String and Double values stored in Array to a file using BufferWriter 使用bufferwriter.readline()时找不到符号 - Cannot find symbol when using bufferwriter.readline()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM