Recommand · October 14, 2021 0

how to transfrom my reading and writing code into realtive path besides with try with resources

I have wrote a code, my code is creating a folder along with txt file and saving succesfully, however I do not like to save folder and file in my local pc, I think I need to use relative path or cache, so my question is how to convert my code to relative path and instead of throwing excepiton, how can I use try with resources ?

my code piece is below;

private Attachment upload(String generatedText, String fileName) throws IOException {

    String filePath = "/C:/folder/createdFolder/" + fileName + ".txt";
        File targetFile = new File(filePath);
        FileWriter writer = new FileWriter(targetFile);
        BufferedWriter buffer = new BufferedWriter(writer);
        String bucketName = "generatedcodes";
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
        ContentDisposition contentDisposition = ContentDisposition
                .filename(fileName + ".txt")
        fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
        FileReader reader = new FileReader(targetFile);
        new BufferedReader(reader);
        byte[] content = generatedText.getBytes();
        InputStream is;
        is = new ByteArrayInputStream(content);
        new BufferedReader(new InputStreamReader(is));
        HttpEntity<byte[]> requestEntity = new HttpEntity<>(generatedText.getBytes(), fileMap);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("object", requestEntity);
        HttpEntity<MultiValueMap<String, Object>> httpEntity =
                new HttpEntity<>(body, headers);
        Object object =, bucketName);
        AttachmentCreate attachmentCreate = new AttachmentCreate();
        // some setters
        attachmentCreate.setUrl("codes/" + fileName + ".txt");
        ResponseEntity<Attachment> attachment = attachmentService.postAttachment(attachmentCreate);
        return attachment.getBody();

Thank you