【问题标题】:Why doesn't FileChannel append to end of file?为什么 FileChannel 不附加到文件末尾?
【发布时间】:2021-06-29 15:49:22
【问题描述】:

我正在尝试使用 Java 从 REST API 下载几个不同的文件。

到目前为止,我正在获取文件,但内容不会附加到输出文件的末尾。

我将FileOutputStream 构造函数从new FileOutputStream(path) 更改为new FileOutputStream(path, true),但不知何故它不起作用。

有人可以提供我所缺少的指针吗?

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class GetXML {

 
    // This Method Is Used To Download A Sample File From The Url
    private static void downloadFileFromUrlUsingNio() {

        String filePath ="config/sample.txt";
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the NO which you want to parse: ");       
        
        
        while(in.hasNextLine()){
        
        String sampleUrl = "e.g.comSearch?NO=" + in.nextLine();
    
 
        URL urlObj = null;
        ReadableByteChannel rbcObj = null;
        FileOutputStream fOutStream  = null;
 
        // Checking If The File Exists At The Specified Location Or Not
        Path filePathObj = Paths.get(filePath);
        boolean fileExists = Files.exists(filePathObj);
        if(fileExists) {
            try {
                urlObj = new URL(sampleUrl);
                rbcObj = Channels.newChannel(urlObj.openStream());
                
                fOutStream = new FileOutputStream(filePath, true);
 
                fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
                
                System.out.println("! File Successfully Downloaded From The Url !");
            } catch (IOException ioExObj) {
                System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());              
            } finally {
                try {
                    if(fOutStream != null){
                        fOutStream.close();
                        System.out.println("fOutStream closed");
                    }
                    if(rbcObj != null) {
                        rbcObj.close();
                        System.out.println("rbcObj closed");
                    }
                } catch (IOException ioExObj) {
                    System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
                }               
            }
        } else {
            System.out.println("File Not Present! Please Check!");
        }
        }
        in.close();
        System.out.println("Scanner Closed");
    }
 
    public static void main(String[] args) {
        downloadFileFromUrlUsingNio();
    }
}

【问题讨论】:

  • 运行时会打印什么?
  • @OneCricketeer "!文件从 URL 成功下载!",fOutStream 关​​闭,rbcObj 关闭,当我有 1 个输入字符串时扫描仪关闭
  • 1) 你没有关闭从fOutStream获取的频道。 --- 2) 你应该检查transferFrom(...) 的返回值。 --- 3) 你应该使用 try-with-resources.

标签: java file-io nio


【解决方案1】:

你写过:

fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);

第二个参数,0,指定数据应该被传输到文件零位置。这个位置是绝对的,你打开文件进行追加并不重要,因为你正在忽略当前频道位置。

注意the documentation 声明,

位置 - 文件中开始传输的位置;必须是非负数

您的代码是处理常见任务的非常规方法。因此,读者很难理解,当你遇到错误时,你也很难得到帮助。由于URL 仅提供InputStream 支持,因此坚持使用流,并避免使用频道。

【讨论】:

  • 感谢您的信息,我在研究时不知何故忽略了这部分。
猜你喜欢
  • 1970-01-01
  • 2014-11-17
  • 1970-01-01
  • 2017-06-15
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
相关资源
最近更新 更多