Java Files.getLastModifiedTime Returning Unexpected Result - java

I'm writing a program that goes through files in a directory and checking each file's last modified date and comparing it with another variable. If the variable matches then I copy said file. I thought this was going to work like a charm but the last modified date being returned seems to be incorrect or there is a weird time zone thing happening.
I'm in the middle of a loop and the file currently being looked at is from 2014-08-18 and was actually last modified at 11:58 PM on that date but the getLastModifiedTime returns 2014-08-19T03:58:37.685611Z. So what gives???? Is this some kind of wacky time off set that I need to handle? This is important because if the last modified date is not accurate I won't know which file to copy....Anyone immediately know what's wrong? This is my first time using this way of iterating through files so I may be missing something.
//Creating a DirectoryStream inside a try-with-resource block
try (DirectoryStream<Path> ds =
Files.newDirectoryStream(FileSystems.getDefault().getPath(dir.getAbsolutePath()))) {for (Path p : ds) {
String lastMod = Files.getLastModifiedTime(p).toString();
String[] splitDte = lastMod.split("T");
if(dateSrc.equals(splitDte[0].toString()))
{
File fileToCopy = p.toFile();
copyFile(fileToCopy,
tempWorkingDir + "\\" + addLeadingZero(logM, 2) + ""
+ addLeadingZero(logDy, 2) + "\\" + fixedValue
+ "\\" + logType + "\\"
);
fileCountProcsd++;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}

The Z indicates that the date is expressed in GMT.

Related

How to set created date of a file that was created in Java code? [duplicate]

This question already has answers here:
Setting file creation timestamp in Java
(4 answers)
Closed 3 years ago.
I have a piece of Java code that will create a new file and fill it with existing data elsewhere. When right clicking on the file and looking at its properties. There will be this property "Created" and "Modified" which are set to the date when the file was created by the code.
I would like to retain the Created/Modified date that the old file had. Is it possible?
ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
if (reader == null)
{
// no data for this node
return false;
}
File output = new File(outputFileName);
reader.getContent(output);
See https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/BasicFileAttributeView.html and/or https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/attribute/BasicFileAttributeView.html
"The setAttribute method may be used to update the file's last modified time, last access time or create time attributes as if by invoking the setTimes method."
File metadata can be fetched as File attributes. Sample example is as below.
File attributes is part of java.nio.file.attribute package.
File file = new File(outputFileName);
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
System.out.println("isDirectory: " + attr.isDirectory());
System.out.println("isOther: " + attr.isOther());
System.out.println("isRegularFile: " + attr.isRegularFile());
System.out.println("isSymbolicLink: " + attr.isSymbolicLink());
System.out.println("size: " + attr.size());
This should give you required details.

How to fix "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values" Android RFID 8500 Zebra

I am trying to develop and application to read and write to RF tags. Reading is flawless, but I'm having issues with writing. Specifically the error "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values"
I have tried reverse-engineering the Zebra RFID API Mobile by obtaining the .apk and decoding it, but the code is obfuscated and I am not able to decypher why that application's Write works and mine doesn't.
I see the error in the https://www.ptsmobile.com/rfd8500/rfd8500-rfid-developer-guide.pdf at page 185, but I have no idea what's causing it.
I've tried forcefully changing the writeData to Hex, before I realized that the API does that on its own, I've tried changing the Length of the writeData as well, but it just gets a null value. I'm so lost.
public boolean WriteTag(String sourceEPC, long Password, MEMORY_BANK memory_bank, String targetData, int offset) {
Log.d(TAG, "WriteTag " + targetData);
try {
TagData tagData = null;
String tagId = sourceEPC;
TagAccess tagAccess = new TagAccess();
tagAccess.getClass();
TagAccess.WriteAccessParams writeAccessParams = tagAccess.new WriteAccessParams();
String writeData = targetData; //write data in string
writeAccessParams.setAccessPassword(Password);
writeAccessParams.setMemoryBank(MEMORY_BANK.MEMORY_BANK_USER);
writeAccessParams.setOffset(offset); // start writing from word offset 0
writeAccessParams.setWriteData(writeData);
// set retries in case of partial write happens
writeAccessParams.setWriteRetries(3);
// data length in words
System.out.println("length: " + writeData.length()/4);
System.out.println("length: " + writeData.length());
writeAccessParams.setWriteDataLength(writeData.length()/4);
// 5th parameter bPrefilter flag is true which means API will apply pre filter internally
// 6th parameter should be true in case of changing EPC ID it self i.e. source and target both is EPC
boolean useTIDfilter = memory_bank == MEMORY_BANK.MEMORY_BANK_EPC;
reader.Actions.TagAccess.writeWait(tagId, writeAccessParams, null, tagData, true, useTIDfilter);
} catch (InvalidUsageException e) {
System.out.println("INVALID USAGE EXCEPTION: " + e.getInfo());
e.printStackTrace();
return false;
} catch (OperationFailureException e) {
//System.out.println("OPERATION FAILURE EXCEPTION");
System.out.println("OPERATION FAILURE EXCEPTION: " + e.getResults().toString());
e.printStackTrace();
return false;
}
return true;
}
With
Password being 00
sourceEPC being the Tag ID obtained after reading
Memory Bank being MEMORY_BANK.MEMORY_BANK_USER
target data being "8426017056458"
offset being 0
It just keeps giving me "GetStatus Write RFID_API_UNKNOWN_ERROR data(x)- Field can Only Take Word values" and I have no idea why this is the case, nor I know what a "Word value" is, and i've searched for it. This is all under the "OperationFailureException", as well. Any help would be appreciated, as there's almost no resources online for this kind of thing.
Even this question is a bit older, I had the same problem so as far as I know this should be the answer.
Your target data "8426017056458" length is 13 and at writeAccessParams.setWriteDataLength(writeData.length()/4)
you are devide it with four. Now if you are trying to write the target data it is longer than the determined WriteDataLength. And this throws the Error.
One 'word' is 4 Hex => 16 Bits long. So your Data have to be filled up first and convert it to Hex.

Process does not exit when launched from Java

I am launching WebTorrent-CLI from within my Java application as a separate process. I am using zt-exec for managing the process. When WebTorrent is launched with the following command, it is supposed to exit after the file at given index (value of --select) has been downloaded.
"D:\downloadmanager\node\webtorrent.cmd" download "magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel" --select 0 --out "D://nf/"
As expected, webtorrent-cli does exit after downloading 0th file when the command above is used to launch it from command line. But when I try the same from within my Java app, it completely ignores the --select option and continues downloading other files in the torrent.
Basically, when launched as a process from Java, webtorrent ignores all the options set (--select, --out or whatever). I should mention that there is nothing wrong with the library because recently I've tried replacing it with commons-exec and that solved nothing. Also, to make sure that the right command is passed while starting the process, I'm printing the command right before calling executor.start(). The command above is copied from the output retrieved from printing the command before the process starts.
This is how the process is started:
#Override
public synchronized void start() throws IOException {
if (mWasDownloadStarted || mWasDownloadFinished) return;
mExec.getCommand().listIterator().forEachRemaining(s -> {
System.out.print(s + " ");
});
mExec.start();
setProcessId();
mWasDownloadStarted = true;
mWasDownloadStopped = false;
}
This is how the command is prepared:
private String buildCommand() {
List <String> command = new ArrayList<>();
command.add("\"" + mManager.mWTLocation + "\"");
command.add("download");
command.add("\"" + mManager.mMagnetUrl + "\"");
if (mManager.mFileIndex >= 0) {
command.add("--select " + mManager.mFileIndex);
}
if (mManager.mSaveTo != null) {
command.add("--out \"" + mManager.mSaveTo + "\"");
}
mManager.mExec.command(command);
String cmdStr = "";
for (String s : command) {
cmdStr = cmdStr.concat(s + " ");
}
return cmdStr.trim();
}
What might be wrong?
Okay, so I was able to fix this issue.
The / character following the path specified as value of --out was causing the problem. In order to fix this, I added a line in node_modules/webtorrent-cli/bin/cmd.js to print the arguments passed to webtorrent:
console.log(process.argv)
With the /, output of this line was something like the following:
[ 'D:\\downloadmanager\\node\\node.exe',
'D:\\downloadmanager\\node\\node_modules\\webtorrent-cli\\bin\\cmd.js',
'download',
'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel',
'--select',
'0',
'--out',
'D:\\nf"' ]
Note the " that is included in the path after D:\\nf. When / is removed from the path, the quote disappears and webtorrent behaves as expected.
I doubt that this is a bug in webtorrent. I think zt-exec (or maybe I) was doing something stupid.
Somewhat unrelated, but I think I should also mention that I had to enclose every value for each option with quotes, even the index, to get rid of other nasty errors (e.g.: Error 87, the parameter is incorrect)

File neither created nor throwing errors

//PRE-SET VARIABLES: symbolsToCheck, time
for (String s : symbolsToCheck) {
String fileName = "daylogs-" + time + "/" + s + ".txt";
File daylog = new File(fileName);
if (!daylog.exists()) {
if (!daylog.createNewFile()) {
System.out.println("ERROR creating day log for " + s);
} else {
System.out.println("Day log created: " + daylog.getCanonicalPath());
}
} else {
System.out.println("ERROR day log already exists for " + s);
}
}
Nothing is outputted from this, and I've confirmed that symbolsToCheck is populated (roughly a dozen strings). I can also confirm that time is set (integer timestamp) well before this code snippet is called. Been scratching my head for quite some time now, any ideas?
I've found the solution from a related post and Tom's suggestion, I've determined that the file creation is breaking due to my attempts to create a new folder and file at the same time, which does not work with createNewFile(). I followed the suggested in the related post and file creation works as expected now.

retry open files in directory

I am trying the following code to open files in a certain directory. The name of the files are assigned by date but some dates are missing. I want to iterate through the dates to get the files and make the code go back 1 day every time it fails to find a file until it finally finds one (currentdate is a global variable and the strange xml element is because I'm using processing).
What I think the code should do is:
try to open the file with the given date.
on error, it goes to catch and gets a new date.
the process is repeated until a valid date is found.
when a valid date is found it goes to the line where break is and exits the loop.
But for some reason it does weird stuff like EDIT # sometimes it jumps too much, especially near the first month #
Is my logic not working for some reason?
Thanks
String strdate=getdatestring(counter);
int counter=0;
while(true){
try{
xmldata = new XMLElement(this, "dir/" + strdate + "_filename.xml" );
break;
}catch(NullPointerException e){
counter +=1;
strdate=getdatestring(counter);
}}
String getdatestring(int counter) {
Date firstdate=new Date();
int daystosum=0;
String strcurrentdate="";
if(keyPressed && key=='7'){
daystosum=-7;
}
daystosum=daystosum-counter;
Calendar c=Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try{
firstdate=formatter.parse("2012-04-13");//first day of the database
}catch(ParseException e){
println(e);
}
c.setTime(currentdate);
c.add(Calendar.DATE,daystosum);
currentdate=c.getTime();
if(currentdate.before(firstdate)){
currentdate=firstdate;
}
strcurrentdate=formatter.format(currentdate);
return strcurrentdate;
}
I believe once you do this,
daystosum=daystosum-counter;
you need to reset the counter as
counter = 0;
otherwise next time it will subtract more bigger number e.g. to start, say daystosum is 0 and counter is 5, after the daystosum=daystosum-counter;, daystosum will become -5. Again you go in the while loop and file is not found then count will increase to 6. In that case you would be getting `daystosum=daystosum-counter; as -5-6 = -11, but you would want it to move to -6. Resetting the counter should ix your issue.
On the other note, I think you can list down the files using file.listFiles() from the parent directory and perform the search on the file names. In that case, you are not attempting to open files again and again.

Categories