How to read file contents in Amazon S3

I have a file in Amazon S3 in an ABCD bucket. I have 3 objects ("folderA/folderB/folderC/abcd.csv") that are folders, and in the last folder I have a .csv file (abcd.csv) . I used the logic to convert it to JSON and upload it back to another file, which is a .txt file in the same folder ("folderA/folderB/folderC/abcd.txt") . I had to upload the file locally to do this. How can I read the file directly and write it back to a text file. The code that I used to write to the file on S3 is below, and I need to read the file from S3.

  InputStream inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_16)); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(json.length()); PutObjectRequest request = new PutObjectRequest(bucketPut, filePut, inputStream, metadata); s3.putObject(request); 
+5
source share
1 answer

You must first get an InputStream object to do your needs.

 S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, key)); InputStream objectData = object.getObjectContent(); 

Pass the InputStream , File Name and path below method to load your stream.

 public void saveFile(String fileName, String path, InputStream objectData) throws Exception { DataOutputStream dos = null; OutputStream out = null; try { File newDirectory = new File(path); if (!newDirectory.exists()) { newDirectory.mkdirs(); } File uploadedFile = new File(path, uploadFileName); out = new FileOutputStream(uploadedFile); byte[] fileAsBytes = new byte[inputStream.available()]; inputStream.read(fileAsBytes); dos = new DataOutputStream(out); dos.write(fileAsBytes); } catch (IOException io) { io.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (dos != null) { dos.close(); } } catch (IOException e) { e.printStackTrace(); } } } 

After you upload your object, read the file and go to JSON and write it to the .txt file after that, you can load the txt file into the desired bucket in S3

+7
source

Source: https://habr.com/ru/post/1208440/


All Articles