Как загрузить байтовый массив, используя Apache Common VFS - PullRequest
0 голосов
/ 21 сентября 2019

Я застрял в загрузке массива байтов с помощью Apache Common VFS, ниже приведен пример загрузки файла с использованием filepath, я погуглил, но я не получаю решение для загрузки файла с использованием байтового массива

    public static boolean upload(String localFilePath, String remoteFilePath) {
    boolean result = false;
    File file = new File(localFilePath);
    if (!file.exists())
        throw new RuntimeException("Error. Local file not found");

    try (StandardFileSystemManager manager = new StandardFileSystemManager();
            // Create local file object
            FileObject localFile = manager.resolveFile(file.getAbsolutePath());

            // Create remote file object
            FileObject remoteFile = manager.resolveFile(
                    createConnectionString(hostName, username, password, remoteFilePath),
                    createDefaultOptions());) {

        manager.init();

        // Copy local file to sftp server
        remoteFile .copyFrom(localFile, Selectors.SELECT_SELF);
        result = true;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

Вышепример взят из здесь

и работает нормально.

Ниже приведен код для загрузки массива байтов с использованием FTPSClient

 private boolean uploadFtp(FTPSClient ftpsClient, byte[] fileData, String fileName) {

 boolean completed = false;
 byte[] bytesIn = new byte[4096];
 try (InputStream inputStream = new ByteArrayInputStream(fileData); OutputStream outputStream =
  ftpsClient.storeFileStream(fileName);) {
  int read = 0;

  while ((read = inputStream.read(bytesIn)) != -1) {
   outputStream.write(bytesIn, 0, read);
  }

  completed = ftpsClient.completePendingCommand();
  if (completed) {
   logger.info("File uploaded successfully societyId");
  }

 } catch (IOException e) {
 logger.error("Error while uploading file to ftp server", e);
 }

 return completed;
}

1 Ответ

0 голосов
/ 21 сентября 2019

См., Например, Пример 6 на https://www.programcreek.com/java-api-examples/?api=org.apache.commons.vfs.FileContent:

/**
 * Write the byte array to the given file.
 *
 * @param file The file to write to
 * @param data The data array
 * @throws IOException
 */

public static void writeData(FileObject file, byte[] data)
        throws IOException {
    OutputStream out = null;
    try {
        FileContent content = file.getContent();
        out = content.getOutputStream();
        out.write(data);
    } finally {
        close(out);
    }
}
...