Content provider with internal storage - java

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

Related

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.
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

File Couldn't Save On All real device Android Studio

//Save PDF file
//Create time stamp
Date date = new Date() ;
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss").format(date);
String filePath = Environment.getExternalStorageDirectory() +"/"+ "Allotment" +timeStamp+ ".pdf";
File myFile = new File(filePath);
try {
OutputStream output = new FileOutputStream(myFile);
pdfDocument.writeTo(output);
output.flush();
output.close();
Toast.makeText(AllotmentDoc.this, "PDF Created Succesfully", Toast.LENGTH_LONG).show();
Toast.makeText(AllotmentDoc.this, "PDF Saved On Memory", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
I want to save my pdf file that's why I wrote some line of code. But it works on some device and doesnt work on some other device. What is the problem. how can i solve it.
I think you are facing this problem in some deviece because of
Environment.getExternalStorageDirectory()
You can use
Environment.getExternalStorageDirectory().getAbsolutePath();
Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. Galaxy Tab 2, Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time.

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.

Adding Time to an Image

I'm trying to take a screenshot using the following code
public void TakeScreenShot() {
String ScreenPrefix = "Screenshot-";
String Time = getTime();
try {
File ScreenName = new File(ScreenPrefix+Time+".png");
BufferedImage image = new Robot().createScreenCapture(new Rectangle(getGameScreen()));
ImageIO.write(image, "PNG", new File(System.getProperty("user.home") + "\\Desktop\\ScreenShots\\"+ScreenName));
JOptionPane.showMessageDialog(null, ScreenName+".png has been saved to your desktop", "Console", JOptionPane.PLAIN_MESSAGE);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if I use the getTime(); method I get the following error:
java.io.FileNotFoundException: C:\Users\Evan\Desktop\ScreenShots\Screenshot-19:30:14 (The filename, directory name, or volume label syntax is incorrect)
but if I change
File ScreenName = new File(ScreenPrefix+Time);
to
File ScreenName = new File(ScreenPrefix);
It works perfectly fine, it just doesn't include the time the screenshot was taken.
if anyone knows how to make the code create the file "Screenshot-Hour:Minute:Seconds"
and is willing to share, it would be very apprieciated
(if you can tell me why I'm getting this error it'd be quite helpful as well)
If you need it, here's my getTime() method:
public static String GetTime() {
Calendar cal = Calendar.getInstance();
cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(cal.getTime());
}
I do have the path "C:\Users\Evan\Desktop\Screenshots" as well, so I don't know why it's telling me I don't when I try to include the time, because it works fine without it
You need to edit the name of the file being saved such that it does not include special characters.
That error is saying the file you're trying to create is invalid.

Error in setting lastmodifieddate in Java

I tried to set the lastmodifeddate of local folder file as the lastmodifieddate of FTP file.
But, in the return value it returns false and date is also not set properly.
Here is the function,
public static void getModifiedDateAndTimeFromFTPFile(String FTPHost, String FTPUserName, String FTPPassword, String FTPRemoteDirectory, String localFilePath, String fileName) {
try{
//get Local File
File fileLocal = new File(localFilePath + fileName);
//Connect to FTP and get the lastmodified time of File.
FTPClient client = new FTPClient();
client.connect(FTPHost);
client.login(FTPUserName, FTPPassword);
client.changeWorkingDirectory(FTPRemoteDirectory);
FTPFile ftpFile = client.listFiles(fileName)[0];
//Get last_modified date of FTP file.
Date ftpFileDate = ftpFile.getTimestamp().getTime();
//Now set date to the Local File.
boolean boolSetTime = fileLocal.setLastModified(ftpFileDate.getTime());
System.out.println(" Was last modified time set successfully ? : " + boolSetTime);
} catch (Exception ex) {
System.out.println("Error : " + ex.toString());
}
}
Can anybody help me by pointing out my mistake?
Thanks
Most probably localFilePath + fileName do not form the intended filename. This won't give you a exception when constructing a File object, but setLastModified(...) would always return false on a non-existing file.
May be it's just a missing path separator?

Categories

Resources