简体   繁体   English

关于通过Java驱动器api下载文件

[英]about download a file by java drive api

I use the "get" method from java drive api, and I can get the inputstream. 我使用Java驱动器api中的“ get”方法,可以获得输入流。 but I cannt open the file when I use the inputstream to creat it. 但是当我使用inputstream创建文件时,无法打开文件。 It likes the file is broken. 好像文件已损坏。

private static String fileurl = "C:\\googletest\\drive\\";

public static void newFile(String filetitle, InputStream stream) throws IOException {
    String filepath = fileurl + filetitle;      
    BufferedInputStream bufferedInputStream=new BufferedInputStream(stream);
    byte[] buffer = new byte[bufferedInputStream.available()];


    File file = new File(filepath);
    if (!file.exists()) {
        file.getParentFile().mkdirs();

        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filepath));
          while( bufferedInputStream.read(buffer) != -1) { 
              bufferedOutputStream.write(buffer);
      }  
          bufferedOutputStream.flush();
          bufferedOutputStream.close();
    }
}

Firstly, C:\\googletest\\drive\\ is not a URL. 首先, C:\\googletest\\drive\\不是URL。 It is a file system pathname. 它是文件系统的路径名。

Next, the following probably does not do what you think it does: 接下来,以下内容可能不会执行您认为的操作:

  byte[] buffer = new byte[bufferedInputStream.available()];

The problem is that the available() call can return zero ... for a non-empty stream. 问题在于, available()调用可以为非空流返回零...。 The value returned by available() is an estimate of how many bytes that are currently available to read ... right now. available()返回的值是当前当前可读取的字节数的估计值 That is not necessarily the stream length ... or anything related to it. 那不一定是流的长度……或与其有关的任何东西。 And indeed the device drivers for some devices consistently return zero, even when there is data to be read. 实际上,即使有数据要读取,某些设备的设备驱动程序也始终返回零。

Finally, this is wrong: 最后,这是错误的:

   while( bufferedInputStream.read(buffer) != -1) { 
          bufferedOutputStream.write(buffer);

You are assuming that read returning -1 means that it filled the buffer. 您假设read返回-1表示它已填充缓冲区。 That is not so. 事实并非如此。 Any one of the read calls could return with a partly full buffer. 任何read调用都可以返回部分已满的缓冲区。 But then you write the entire buffer contents to the output stream ... including "junk" from previous reads. 但是随后您将整个缓冲区的内容写入输出流中,包括先前读取的“垃圾”。


Either or both of the 2nd and 3rd problems could lead to file corruption. 第二个和第三个问题中的一个或两个都可能导致文件损坏。 In fact, the third one is likely to. 实际上,第三个可能

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

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