Naming a text file with a date and time parameter + a string

in my project I have to encrypt some notes of patients what i do is I get the "LocalDateTime dateTime" through a parameter and create a file with that name + "Encryptedtxt" + ".txt". And additionally I wanted to add the doctors id too but first of all I need to do the first part. So i attempted the task but it's not working as I'm expecting. This is the part where I'm creating the file,

    public void txtEncrypt(String text, LocalDateTime localDateTime) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
        try {

            String subfolder = "Encryption" + File.separator + "txt";
            String fileName = localDateTime + "-encryptedText.txt";
            File file = new File(subfolder, fileName);
            FileOutputStream outStream = new FileOutputStream(file);

This only works partially. This is the output

This only adds the localDate time "-encryptedText.txt" is missing

This only adds the localDate time ". -encryptedText.txt" is missing. Can someone kindly help me out in this one?

Upvotes: 1

Views: 726

Answers (3)

Coder Bb
Coder Bb

Reputation: 1

HH:mm:ss is invaild for filename,so this filename is filtered

Upvotes: -1

CUB5
CUB5

Reputation: 57

I think you should call dateFormat.format(localDateTime), or something like that, and get an string to add to the "-encryptedText.txt", to sum up, you need to add an string to another string, you can not add a string to an object

Upvotes: 0

user19443549
user19443549

Reputation:

you can't use local date time object directly in file name, it will give you text value like - 2023-01-07T14:38:00.502959700 so you can't create file name with colon(:) in it.

You need to format your local date time object in any permissible format then it will work. You can try below code -

    String subfolder = "Encryption" + File.separator + "txt";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmmss");
    String fileName = localDateTime.format(formatter) + "-encryptedText.txt";
    File file = new File(subfolder, fileName);
    FileOutputStream outStream = new FileOutputStream(file);

Upvotes: 3

Related Questions