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

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.
Can someone kindly help me out in this one?

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);

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

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

Related

Creating a new folder each time Selenium WebDriver takes a screenshot

// Take screenshot method
static void captureScreenshot(String fileName) throws IOException {
// Take the screenshot and store as file format
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Open the current date and time
String timestamp = new SimpleDateFormat("dd_MM_yyyy__hh_mm_ss").format(new Date());
//Copy the screenshot on the desire location with different name using current date and time
Cache.copyFile(scrFile, new File("C:\\Users\\Kiko Kikostov\\IdeaProjects\\AboutPagesBanerScreenSizes\\15inchScreenSize\\Asia\\" + fileName + " " + timestamp + ".png"));
String st = scrFile.getAbsolutePath();
String str = scrFile.getParent();
scrFile = new File(str+"/"+ "/" + fileName);
}
This works fine for me but I want to implement that every time the test is run a new folder or subfolder is created inside the existing one.
You can create a directory with the os
import os
directory = "MyFolder"
parent_dir = "D:/Pycharm projects/"
path = os.path.join(parent_dir, directory)
os.mkdir(path)
print("Directory '% s' created" % directory)
So, for your usecase should be something like this:
import os
parent_dir="C:\\Users\\Kiko Kikostov\\IdeaProjects\\AboutPagesBanerScreenSizes\\15inchScreenSize\\Asia\\";
// Take screenshot method
static void captureScreenshot(String fileName) throws IOException {
// Take the screenshot and store as file format
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Open the current date and time
String timestamp = new SimpleDateFormat("dd_MM_yyyy__hh_mm_ss").format(new Date());
// Assuming you want a folder with the timestamp
directory = timestamp;
path = os.path.join(parent_dir, directory)
os.mkdir(path)
//Copy the screenshot on the desire location with different name using current date and time
Cache.copyFile(scrFile, new File(directory + fileName + " " + timestamp + ".png"));
String st = scrFile.getAbsolutePath();
String str = scrFile.getParent();
scrFile = new File(str+"/"+ "/" + fileName);

Is there any way to SFTP a file with filename generation includes yyyyMMddHHmmss

I'm trying to SFTP a file and its filename includes yyyyMMddHHmmss.
Once file generated I need to SFTP to remote server and since there is a time difference between the file generation time and the time I'm trying to SFTP, I'm getting (No such file or directory) error.
ex.
File1 : Extract_20181227172954.txt
My sftp code is trying to find the file with file name:
Extract_20181227173000.txt
//file generation
File = getFilePath() + "Extract_"+ + this.getFileDate2() + ".txt";
PrintWriter pw = new PrintWriter(File);
//Extract_20181227172954.txt --sample file extracted
//sftp method
public boolean upload( String filePath, String fileName) {
JSch jSch = new JSch();
File localFile = new File(filePath + fileName);
this.channelSftp.put(new FileInputStream(localFile), localFile.getName());
}
//sftp is trying to find file Extract_20181227173000.txt instead of Extract_20181227172954.txt
//calling the sftp method
this.sftpSucess = sftp.upload(getFilePath(), "Extract_"+ + getFileDate2() + ".txt");
//filedate method
SimpleDateFormat fileDate2 = new SimpleDateFormat("yyyyMMddHHmmss");
private String getFileDate2() {
Calendar calendar = Calendar.getInstance();
return this.fileDate2.format(calendar.getTime());
}
When you call the getFileDate2(), you are using Calendar.getInstance(), for each time you do that you get the current time. Calling it on the second time the file is not found, since the time used in the file name is in the past and you got a most recent time.
You should call the Calendar.getInstance() once and store the date in your object instead of getting an new instance every time. With the stored date you will be able to fetch the saved file.
From the docs:
getInstance(): Gets a
calendar using the default time zone and locale. The Calendar returned
is based on the current time in the default time zone with the default
locale. Returns: a Calendar.

Cannot create file with Java using the Parent and Child parameters of the new File constructor

I am trying to create a file using Java. I want to create this file in a sub-folder of my "Documents" directory. I want this sub-folder to be based today's date.
I thought I new how to use the File class and file.mkdirs() method properly, but I guess I don't.
Here is what I have:
public class FileTest {
private static final String sdfTimestampFormat = "yyyy-MM-dd HH:mm:ss Z";
private static final SimpleDateFormat timestampSDF = new SimpleDateFormat(sdfTimestampFormat);
private static final String sdfDirFormat = "yyyy-MM-dd";
private static final SimpleDateFormat dirSDF = new SimpleDateFormat(sdfDirFormat);
public static void test() throws FileNotFoundException, IOException{
Date rightNow = new Date();
String data = "the quick brown fox jumps over the lazy dog";
String path = System.getProperty("user.home");
String filename = "file.txt";
String directory_name = path + System.getProperty("file.separator") + "Documents" + System.getProperty("file.separator") + dirSDF.format(rightNow);
File file = new File(directory_name, filename);
if(file.mkdirs()){
String outstring = timestampSDF.format(rightNow) + " | " + data + System.getProperty("line.separator");
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(outstring.getBytes());
fos.close();
}
}
}
What is happening is that the following directory is created:
C:\Users\<username>\Documents\2018-08-03\file.txt\
I was under the impression that the Parent parameter of the new File constructor was the base directory, and the Child paramater of the new File constructor was the file itself.
Is this not the case? Do I need two File objects, one for the base directory and another for the file?
What I want is this:
C:\Users\<username>\Documents\2018-08-03\file.txt
Thanks.
mkdirs() will do directories (if they don't exist) for each element in your path.
So you can use file.getParentFile().mkdirs() to not make a directory for your file.txt
Edit: Something to consider
mkdirs() only returns true if it actually created directories. If they already existed or there was a problem creating them it will return false
Since you are trying to run this multiple times to append to your text your logic will not run inside your if-statement
I would change it to:
boolean created = true;
if(!file.getParentFile().exists()) {
created = file.getParentFile().mkdirs();
}
if (created) {
String outstring = timestampSDF.format(rightNow) + " | " + data + System.getProperty("line.separator");
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(outstring.getBytes());
fos.close();
}

Content provider with internal storage

I'm writing an app in which I'm saving photos in internal storage. I'm using solution from this blog
I know names of two files before, so I can have in a code, but in my app there will be also a gallery. So my question is: how to save files without knowing their name(file name is generated using date and time)? Content provider's oncreate starts during initialisation so how to pass new files names to content provider?
Thanks in advance.
In the content provider class remove in onCreate the file creation completely.
public static String lastPictureSaved = "";
Change the function openFile. There the filename will be made accordig to date time and the file created.
Date date = new Date();
date.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
String datetimestr = formatter.format(date);
lastPictureSaved = getContext().getFilesDir() + "/" + datetimestr + ".jpg";
File f = new File(lastPictureSaved);
try
{
f.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
Log.d(TAG, e.getMessage());
}
in the Host activity change
File out = new File(getFilesDir(), "newImage.jpg");
to
File out = new File(MyFileContentProvider.lastPictureSaved);

How to append date and time in multiple file in a folder while moving it to another folder

public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
Source Folder
File source = new File("D:\\A1\\");
File dest = new File("D:\\A2\\");
File[] files = source.listFiles();
for (File file: source.listFiles()){
String x=(source+"\\"+file.getName());
String y=(dest + "\\"+ file.getName());
File f1 = new File(x);
f1.renameTo(new File(y));
}
This code is moving the file from source to destination folder but i want when file moved to destination folder . it appends the the system date with its name
Please Help
You need to append the timestamp to the filename, at best right before the extension.
Note that operating systems may not allow some characters to appear in a filename, for example the colon and the slash may not be use on windows, so yo need to find a substitue for them.
Also you need to check the return value of renameTo to check whether the file was realy moved or not.
returns true if and only if the renaming succeeded; false otherwise
You could try something like this:
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String ts = dateFormat.format(date);
File source = new File("D:\\A1\\");
File dest = new File("D:\\A2\\");
for (File file : source.listFiles()) {
String x = (source + "\\" + file.getName());
String y = (dest + "\\" + addTimestamp(file.getName(), ts));
File f1 = new File(x);
if(f1.renameTo(new File(y))){
System.out.println("moved: " + y);
} else {
System.out.println("unable to move: " + y);
}
}
}
private static String addTimestamp(String name, String ts) {
int lastIndexOf = name.lastIndexOf('.');
return (lastIndexOf == -1 ?
name + "_" + ts
:
name.substring(0, lastIndexOf) + "_" + ts +
name.substring(lastIndexOf))
.replaceAll("[\\/:\\*\\?\"<>| ]", "_");
}
Finally for moving files better use Files#move as the javadoc of renameTo itself suggests.
You can do it this way
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
Date date = new Date();
y=(dest + "\\"+ file.getName()+dateFormat.format(date));
As per Java Docs of File#renameTo method, it is a platform dependent implementation and it may not work as you expect.
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
Note that the Files class defines the move method to move or rename a
file in a platform independent manner.
You can alternatively use Files#move method. It is a Platform Independent method.
Hope this helps

Categories

Resources