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.
Related
I am exporting a .jar file from a GUI built in Netbeans IDE. It works fine within Netbeans but once it is exported, some logic in the code does not execute properly.
I have tried debugging by running test cases displaying which items are passing through the if clauses. It seems to work well in IDE but not when it is run through .jar file.
for(Chamber chamber: chs)
{
if(!scheduledTools.containsKey(chamber))//unscheduled chambers
{
JOptionPane.showMessageDialog(this, chamber.getName()+": is unscheduled");
model.addElement(chamber.getName());
}
else//scheduled
{
if((scheduledTools.get(chamber).size()/range) > .25)
{
System.out.println("Range: " +range+" Scheduled: " +scheduledTools.get(chamber).size());
System.out.println("Cannot use this chambers:" +chamber.getName());
JOptionPane.showMessageDialog(this, chamber.getName()+": Cannot use this chamber");
}
else{
System.out.println("Scheduled but can use"+chamber.getName());
altModel.addElement(chamber.getName());
}
}
}
alternateChambers.setModel(altModel);alternateChambers.setSelectedIndex(0);
suggestedChambers.setModel(model);suggestedChambers.setSelectedIndex(0);
if(altModel.size()>1){JOptionPane.showMessageDialog(this, "Scheduled but can use these chambers:"+altModel);}
After making the necessary queries in seekDates method below:
private void seekDates(ResultSet rs) throws SQLException
{
ArrayList<String> entries;
//get how many dates we have so we can update progressbar
int results = 0;
setProgress(results);
if(rs.last()){results=rs.getRow();rs.beforeFirst();}
// processing returned data and printing into console
while(rs.next()) {
String scheduledChamber = rs.getString(2);
for(Chamber chamber : chambers){
//if the scheduled tool is a thermal chamber
//chambers get listed so far
if(!scheduledChamber.trim().toLowerCase().contains(chamber.getName().toLowerCase()))
{}//print chambers im not saving
else{
if(scheduledTools.containsKey(chamber))
{
//if key already used, just grab the list and add date
entries = scheduledTools.get(chamber);
entries.add(rs.getString(1).split(" ")[0]);
}
else
{
//if chamber hasnt been saved, add chamber and date
entries = new ArrayList<String>();
entries.add(rs.getString(1).split(" ")[0]);
scheduledTools.put(chamber, entries);
}
//System.out.println("Just saved this chamber:" +scheduledChamber+" with this date:" +scheduledTools.get(chamber));
}
;
}
publish(rs.getRow());
Thread.yield();
setProgress(100*(rs.getRow()/results));
}
}
The GUI should display the chambers found in the queries in one text field while displaying the rest of the chambers in another text field.
When I run this in the IDE. I get the correct outcome but once I compile using the package-for-store option in the build.xml file, the outcome then just lists all of the chambers in one text field.
In the .jar file, it seems that all of the chambers only satisfy the first if clause and none of the others.
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.
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.
I'm doing a project to catering item hiring service. They want to save the date and time customer hire their items also save the date and time customer return them. Of course any of those not gona be actual at the movement date or time. So first of all I'm trying to find to save any date and time. Other activities will concern later. So I came up with little table. like given below.
ID | Name | Value | Date | Time
(int) | (Varchar) |( Double) | (DateTime) | (DateTime)
And I used this cord to save data.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
String date=new SimpleDateFormat("yyyy-MM-dd").format(dat.getDate());
String time = String.valueOf(dateSpinner.getValue()).split(" ")[3];
try {
new JDBC().putData("INSERT INTO work (name, balance, date) VALUES ('"+txtName.getText()+"',"+txtValue.getText()+"', '"+date+"', '"+time+"') ");
JOptionPane.showMessageDialog(null, "value saved");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, this.getClass().getName() +" "+e);
}
}
When I'm entering data I'm having
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3" .
Help me to find the error of this cord and save any time. Actually I can save any date using String Date variable. I saved some demo data before I added time field to table. But I'm having this problem when I'm trying to save time. I am using date Spinner to save time. But I can't format it as HH-mm--ss. If you know another time saving feature please let me know. Please help me.
This line:
String time = String.valueOf(dateSpinner.getValue()).split(" ")[3];
Is the same as this, just done on a single line
String[] splitArr = String.valueOf(dateSpinner.getValue()).split(" ");
String time = splitArr[3];
The error you are getting is saying that there is not 4 elements in the split array. Put in the below piece of code to debug what you are getting so you know what is happening in that single line
String[] splitArr = String.valueOf(dateSpinner.getValue()).split(" ");
for(int i = 0; i < splitArr.length; i++)
{
System.out.println("Element number " + i + " is \"" + splitArr[i] + "\"");
}
Then you can update your insert appropriately. Sorry I cant be of more help but we do not know what datespinner is or what datespinner.getValue() returns so do the above to help debug your code.
Nearly 1 month my program worked fine, but today im getting the error above when starting it.
The error comes up in this line:
sounds.put(key, (Clip)AudioSystem.getLine(new Line.Info(Clip.class)));
I have no idea why.
After i read the accepted answer here, i reinstalled eclipse, deleted metadata and so on, but the error still comes up.
The code is to 100% right, but any way ill post the code near the error:
protected SoundArchive(String soundArchive, boolean debugFrame){
f = new File(this.getClass().getResource("../" + soundArchive).toString().substring(5)).listFiles();
sounds = new HashMap<String, Clip>();
try{
for(int i = 0; i < f.length; i++){
String key = f[i].toString().split("\\\\")[f[i].toString().split("\\\\").length - 1].split("\\.")[0];
sounds.put(key, (Clip)AudioSystem.getLine(new Line.Info(Clip.class)));
sounds.get(key).open(AudioSystem.getAudioInputStream(f[i]));
}
}
catch(Exception e){
e.printStackTrace(System.out);
}
if(debugFrame) debugFrame();
}
So, does anyone know what i have to do now? I've my back to the wall....