简体   繁体   中英

Why doesn't FileChannel append to end of file?

I am trying to download a few different files from a REST API using Java.

So far, I am getting the files, but the content won't append to the end of an output file.

I changed the FileOutputStream constructor from new FileOutputStream(path) to new FileOutputStream(path, true) but somehow it does not work.

Can somebody please provide pointers to what I am missing?

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();
    }
}

You have written:

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

The second parameter, 0, specifies that data should be transferred to the file at position zero. The position is absolute, and it doesn't matter that you opened the file for append, because you are ignoring the current channel position.

Note the documentation that states,

position - The position within the file at which the transfer is to begin; must be non-negative

Your code is an unconventional approach to a common task. As such, it's hard for readers to comprehend, and, when you encounter mistakes, hard for you to get help. Since URL only offers InputStream support, stick with streams, and avoid channels.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM