Hi I need to copy the files stored in an array to a folder in the destination using java 7 copyfilemethod. I donot get any error, but it doesnt copies the files.Please help to copy the files from source to destination folder.Thanks in advance
public class copyFiles {
public static void main(String[] args) {
Date date = new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String date2 = ((month+1) + "/" + (day) + "/" + year);
System.out.println("the current date is " + date2);
String path = "c://Users//Desktop//Test";
System.out.println("PATH::"+path);
File directory = new File(path);
File[] myarray;
myarray = directory.listFiles();
try{
for (int j = 0; j < myarray.length; j++) {
if(myarray[j].isDirectory()){
SimpleDateFormat sdf = new SimpleDateFormat("M/D/YY");
String dt = sdf.format(myarray[j].lastmodified());
if(dt.compareTo(date2) == 0){
File[] myarray1 - myarray[j].listFiles();
for(int i = 0; i < myarray1,length; i++){
if(myarray1[i].isDirectory()){
System.out.println("Do nothing");
}
else
{
SimpleDateFormat sdf1 = new SimpleDateFormat("M/D/YYYY");
String dt1 = sdf1.format(myarray1[i].lastmodified());
if(dt1.compareTo(date2) == 0){
System.out.println(myarray1[i]);
File Source = myarray1[i];
File Dest = new File("c://Users//Desktop//destination");
CopyFileusingJava7Files(source, dest);
}
}
}
}
}
}
}
catch(Exception e){
System.out.println("The file is not found");
}
}
Private Static void CopyFileusingJava7Files(File source, File dest) throws IOException{
Files.copy(source.toPath(), dest.toPath());
}}
Try it with administration rights. Normally a JAR doesn't have that much rights unless you define the rights you need.
I'll share some intresting links below where you can find information about defineing permissions. This is possible with a file: "MANIFEST.MF".
Manifest Basics
Defining Permissions in the mainfest
Related
I have an app with data files (some images and xml files) i have packed them up in a zip file.
I open the file with zipme and save the files. I used this code for that
private void save1( ) {
InputStream is;
FileChooser.showOpenDialog(".zip", new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e != null && e.getSource() != null) {
String file = (String)e.getSource();
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream is = fs.openInputStream(file);
ZipInputStream zipStream = new ZipInputStream(is);
ZipEntry entry;
// create a buffer to improve copy performance later.
byte[] buffer = new byte[2048];
while ((entry = zipStream.getNextEntry()) != null) {
String s = entry.getName();
String outdir = FileSystemStorage.getInstance().getAppHomePath();
if (outdir.length() > 0) {
outdir = outdir ;
}
String outpath = outdir + "/" + entry.getName();
OutputStream output = null;
try {
output = FileSystemStorage.getInstance().openOutputStream(outpath);
int len = 0;
while ((len = zipStream.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
} finally {
// we must always close the output file
if (output != null) {
output.close();
}
}
} } catch (IOException ex) {
Log.p(ex.getMessage(), 0); } } }});}
i see in netbeans that in the simulator the files are saved to
users/.cn1
So this works on the desktop
To fetch the image i use
String outdir = FileSystemStorage.getInstance().getAppHomePath();
Image uur1 = EncodedImage.create(outdir + "/West.jpg");
i also tried without outdir but also no luck.
What do i wrong.
This should work without the extra slash:
Image uur1 = EncodedImage.create(outdir + "West.jpg");.
Notice that this code is case sensitive so make sure the file has the right casing. Is this failing on the simulator, if so place a breakpoint on the loading code and make sure the file is physically there
The answer i found on my question is:
1 No extra slash as Shai Among suggested:
2 Make a inputstream for enecodedimage.create() instead of only a string with the path to the file
Without the second part the app doesn't run correctly in the simulation and on the device
FileSystemStorage fs = FileSystemStorage.getInstance();
String outdir = FileSystemStorage.getInstance().getAppHomePath();
String outpath = outdir + West.jpg;
InputStream isk = fs.openInputStream(outpath);
Image uur = EncodedImage.create(isk);
I have studied the Files, Storage and Networking instructions on the Codename One website. I am trying to
save files selected by the Codename One filechooser to the device (simulator, Android, iPhone)
retrieve the files saved locally in whatever device they got saved on.
Here is the code I used:
final Button getFileChooser = new Button("Get file chooser");
getFileChooser.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (FileChooser.isAvailable()) {
FileChooser.showOpenDialog(".pdf, .jpg, .jpeg, .png", e2-> {
String file = (String)e2.getSource();
if (file == null) {
hi.add("No file was selected");
hi.revalidate();
} else {
String extension = null;
if (file.lastIndexOf(".") > 0) {
extension = file.substring(file.lastIndexOf(".")+1);
ToastBar.showMessage("1: " + file, FontImage.MATERIAL_CHECK);
rawFilename.setText("raw: " + file);
//java.util.List<String> filepathParsed = StringUtil.tokenize(file, "[/.]");
StringBuilder hi = new StringBuilder(file);
if (file.startsWith("file://"))
hi.delete(0, 7);
int lastIndexPeriod = hi.toString().lastIndexOf(".");
Log.p(hi.toString());
String ext = hi.toString().substring(lastIndexPeriod);
String hmore = hi.toString().substring(0, lastIndexPeriod -1);
String hi2 = hmore +/* "/file" +*/ ext;/*hi;*/
Log.p("hi2 = " + hi2);
secondFilename.setText("2nd: " + hi2);
//secondFilename.setText((String)evt.getSource());
try {
saveFileToDevice(file, ext);
} catch (URISyntaxException e) {
e.getMessage();
}
//sendFileViaEmail(hi2, file);
} else {
ToastBar.showMessage("2: " + file + " " + extension, FontImage.MATERIAL_CHECK);
}
}
hi.revalidate();
});
}
}
});
protected void saveFileToDevice(String hi, String ext) throws URISyntaxException{
URI uri = new URI(hi);
String path = uri.getPath();
Log.p("uri path: " + uri.getPath() + " ; scheme: " + uri.getScheme());
/*if (path.contains("..jpg")) {
int indexLastPeriodBeforeExt = path.lastIndexOf(".");
path = path.substring(0, indexLastPeriodBeforeExt) + path.substring(indexLastPeriodBeforeExt+ 1);
Log.p("new path: " + path);
}*/
if (Display.getInstance().getPlatformName().equals("and"))
path = "file://" +path;
String home = FileSystemStorage.getInstance().getAppHomePath();
char sep = FileSystemStorage.getInstance().getFileSystemSeparator();
String userDir = home + sep + "myapp";
/*if (hi.startsWith("file://")) {
hi = hi.substring(7);
}*/
int index = hi.lastIndexOf("/");
hi = hi.substring(index + 1);
Log.p("hi after substring 7: " + hi);
FileSystemStorage.getInstance().mkdir(userDir);
String fPath = userDir + sep + hi ;
/* if (hi.contains("..jpg")) {
int indexLastPeriodBeforeExt = hi.lastIndexOf(".");
hi = hi.substring(0, indexLastPeriodBeforeExt) + hi.substring(indexLastPeriodBeforeExt+ 1);
Log.p("new hi: " + hi);
}*/
Log.p("does it exist? " + FileSystemStorage.getInstance().exists(userDir));
String imageFile = userDir + sep + hi;
String[] roots = FileSystemStorage.getInstance().getRoots();
if (roots.length > 0) {
for (int i = 0; i < roots.length; i++)
Log.p("roots" + i + " " + roots[i]);
}
try {
String[] files = FileSystemStorage.getInstance().listFiles(userDir);
for (int i = 0; i < files.length; i++) {
Log.p(i + " " + files[i]);
//secondName = files[files.length-1];
Log.p("secondname: " + secondName);
}
sendFileViaEmail(imageFile, ".jpg");
} catch (IOException e) {
e.getMessage();
}
}
protected void sendFileViaEmail(String hi2, String file) {
Message m = new Message("Test message");
//m.getAttachments().put(file, "image/jpeg");
m.setAttachment(hi2);
m.setAttachmentMimeType(Message.MIME_IMAGE_JPG);
//m.setMimeType(Message.MIME_IMAGE_JPG);
//m.getAttachments().put(imageAttachmentUri, "image/png");
Display.getInstance().sendMessage(new String[] {"myemail#example.com"}, "test message cn1", m);
}
I added the getFileChooser button to my Form after importing the cn1-filechooser library to my project and refreshed libs. The filechooser works -- I tried it on the simulator, Android device and iPhone.
My issue is here:
String file retrieves what looks like a URI. I tried to convert the URI to a File and when I run the following code to see that the files are stored I see them in my logs, although in a funny order, which I'm ok with.
String[] files = FileSystemStorage.getInstance().listFiles(userDir);
for (int i = 0; i < files.length; i++) {
Log.p(i + " " + files[i]);
//secondName = files[files.length-1];
Log.p("secondname: " + secondName);
}
How do retrieve a valid, uncorrupted version of this file from FileSystemStorage? Am I storing it wrong? Whenever I run the method to send the file via email, it opens Outlook (on my Desktop) but no files is attached? (I assume that the file is invalid/corrupted when trying to retrieve it from FileSytemStorage -- please help.) I hardcoded .jpg as MIME-type but only as a test; my goal is to be able to save/restore .pdf, .png, .jpg, and.jpeg files.
Thanks!
**EDIT: ** This seems to show that the file was actually saved to my app's storage. How do I stream the content of the file be copied/uploaded or emailed from my app?
Mobile phones don't allow that. They don't have a file system like desktops have. So file chooser really launches a tool to help you pick a file from a different app, this file is then copied to your local app sandbox where you can get access to the content of the app.
Naturally this won't work for save as it would mean you could potentially corrupt a file within another application so you are restricted from writing to the directories of other applications installed or even knowing which applications are installed and where...
To transfer a file to a different app you have the share intent which you can use via the share button or the low level API's in display. This allows you to send an image to whatsapp or similar functionality that makes sense in a mobile phone.
This question already has answers here:
how to read all cell value using Apache POI?
(2 answers)
Closed 7 years ago.
I had created my script to validate my actual result and expected result , .
As there is too many link to validated script will get too much of coding m so i need to convert this into Data Driven Case ,.
Where Webdriver will get URL , xpath ,expected value from excel .
But dont know how to proceed , .
A demo code is much appreciated
Here is my current script :
public void test() throws Exception
{
String home_logo_url="158321";
String enough_talk_promo="1057406";
System.out.println("Check for home_logo_url");
driver.get(baseUrl);
String SiteWindow = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[#id='logo']/a")).click();
for (String PromoWindow : driver.getWindowHandles())
{
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
String script = "return rlSerial;";
String value = (String) ((JavascriptExecutor)driver).executeScript(script);
Assert.assertEquals(value,home_logo_url);
driver.close();
driver.switchTo().window(SiteWindow);
System.out.println("Pass");
System.out.println("Check for enough_talk_promo");
driver.get(baseUrl + "/category/tournaments/");
driver.findElement(By.xpath("//*[#id='content']/div/div[4]/aside/div/div/p[1]/a")).click();
for (String PromoWindow : driver.getWindowHandles())
{
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
String sr_enough_talk_promo = (String) ((JavascriptExecutor)driver).executeScript(script);
Assert.assertEquals(sr_enough_talk_promo,enough_talk_promo);
driver.close();
driver.switchTo().window(SiteWindow);
System.out.println("Pass");
}
How to iterated to each rows and get my test case run !!!
It is much helpful , if some one can convert my existing code to work on excel sheet .
Thanks
i was working on a project in Spring that read from an excel (.xls) and this was my code if can help
private List<String> extraire (String fileName) throws IOException {
List<String> liste = new ArrayList();
FileInputStream fis = new FileInputStream(new File(fileName));
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator < Row > rowIterator = null;
rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
int i = 0;
row = (HSSFRow) rowIterator.next();
Iterator < Cell > cellIterator = row.cellIterator();
while ( cellIterator.hasNext()) {
Cell cell = cellIterator.next();
i++;
/**
* For verifying if a line is empty
*/
if (i % 29 == 0 || i == 1) {
while ( cellIterator.hasNext() && cell.getCellType() == Cell.CELL_TYPE_BLANK) {
cell = cellIterator.next();
}
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
String cellule = String.valueOf(cell.getNumericCellValue());
liste.add(cellule);
break;
case Cell.CELL_TYPE_STRING:
liste.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
cellule = " ";
liste.add(cellule);
break;
}
}
}
fis.close();
return liste;
}
in my controller :
List<String> liste = new ArrayList();
liste = extraire(modelnom);
for (int m=0, i=29;i<liste.size();i=i+29) {
if(i % 29 == 0) {
// i=i+29 : begin from the second line first coll
// m is line
m++;
}
String matricule = (String)liste.get(29*m).toString().trim();
float mat = Float.parseFloat(matricul); // From String to float
employe.setMatricule((int)mat); //reading mat as an int
// ... your Code
}
I have no idea in what extend GAE is not easy to understand :(
My servlet manipulate a json string and then I'm trying to store it in datastore.
When I run the application I'm getting this output:
Jan 27, 2014 6:59:04 PM com.google.appengine.api.datastore.dev.LocalDatastoreService load
INFO: The backing store, D:\Android\IntelliJ IDEA\workspace\EyeBall\AppEngine\out\artifacts\AppEngine_war_exploded\WEB-INF\appengine-generated\local_db.bin, does not exist. It will be created.
1
2
3
4
5
7
***
***
***
***
***
8
9
Although it's mentioned that local_db.bin will be created but when I navigate to that directory the file is not there. Also, when I open http://localhost:8080/_ah/admin/datastore in browser nothing displays in Entity Kind drop down list.
So wtf happene to local_db.bin? Why it doesn't generates?
any suggestion would be appreciated. thanks.
==================
UPDATE:
I added my code based on request.
private static final String NO_DEVICE_ID = "FFFF0000";
private static final String SAMPLE_JSON = "{\"history\":[{\"date\":null,\"info\":null,\"title\":\"Maybank2u.com\",\"url\":\"https://www.maybank2u.com.my/mbb/Mobile/info.do\",\"visits\":14},{\"date\":null,\"info\":null,\"title\":\"Maybank2u.com\",\"url\":\"https://www.maybank2u.com.my/mbb/Mobile/adaptInfo.do\",\"visits\":4},{\"date\":null,\"info\":null,\"title\":\"Maybank2u.com\",\"url\":\"http://www.maybank2u.com.my/mbb_info/m2u/public/personalBanking.do\",\"visits\":16},{\"date\":null,\"info\":null,\"title\":\"Maybank2u.com Online Financial Services\",\"url\":\"https://www.maybank2u.com.my/mbb/m2u/common/M2ULogin.do?action=Login\",\"visits\":52},{\"date\":null,\"info\":null,\"title\":\"BBC\",\"url\":\"http://www.bbc.co.uk/persian/\",\"visits\":16}]}";
private static final String QUERY_HISTORY_DEVICE = "SELECT m FROM HistoryDeviceJPA m WHERE m.userUUID = :keyword ORDER BY m.domain ASC";
private static final String QUERY_HISTORY = "SELECT m FROM HistoryJPA m WHERE m.pageAddress = :keyword";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// displayError(response, "The page doesn't support httpGet");
String deviceId = NO_DEVICE_ID;
String content = SAMPLE_JSON;
System.out.println("1");
HistoryBrowser historyBrowser = parseJson(content);
if(historyBrowser == null)
return;
System.out.println("2");
List<HistoryBrowser.BrowserInfo> historyList = historyBrowser.getHistory();
if(historyList == null)
return;
System.out.println("3");
List<HistoryDeviceJPA> historyDeviceJPAList = new ArrayList<HistoryDeviceJPA>(historyList.size());
for(int i=0; i<historyList.size(); i++) {
try {
HistoryBrowser.BrowserInfo browser = historyList.get(i);
HistoryDeviceJPA historyDeviceJPA = new HistoryDeviceJPA();
historyDeviceJPA.setUserUUID(deviceId);
historyDeviceJPA.setDomain(getDomainName(browser.getUrl()));
historyDeviceJPA.setPageAddress(browser.getUrl());
historyDeviceJPA.setPageTitle(browser.getTitle());
historyDeviceJPA.setPageVisits(browser.getVisits());
historyDeviceJPAList.add(historyDeviceJPA);
} catch (URISyntaxException e) {
System.out.println(e.getMessage());
}
}
System.out.println("4");
// get history of device from data store
EntityManager em = EMF.get().createEntityManager();
Query q = em.createQuery(QUERY_HISTORY_DEVICE).setParameter("keyword", deviceId);
#SuppressWarnings("unchecked")
List<HistoryDeviceJPA> dbList = (List<HistoryDeviceJPA>) q.getResultList();
System.out.println("5");
// If there is no result (shows there is no record for that device)
if(dbList == null)
addHistoryDeviceJPAToDs(historyDeviceJPAList);
else {
System.out.println("7");
// find each item in datastore and replace them if needed
// if current page visit is less ot equal than previous visit don't do anything (remove item form historyDeviceJPAList)
outerLoop:
for(int i=0; i<historyDeviceJPAList.size(); i++) {
HistoryDeviceJPA deviceItem = historyDeviceJPAList.get(i);
System.out.println("***");
for(int j=0; j<dbList.size(); j++) {
HistoryDeviceJPA dbItem = dbList.get(j);
if(deviceItem.getPageAddress().equalsIgnoreCase(dbItem.getPageAddress())) {
if(deviceItem.getPageVisits() > dbItem.getPageVisits()) {
long diff = deviceItem.getPageVisits() - dbItem.getPageVisits();
dbItem.setPageVisits(deviceItem.getPageVisits());
HistoryJPA historyJPA = findHistoryJPA(dbItem.getPageAddress());
historyJPA.setPageVisits(historyJPA.getPageVisits() + diff);
// update datastore
addHistoryDeviceJPAToDs(dbItem);
addHistoryJPAToDs(historyJPA);
// don't check other items of j list
break outerLoop;
}
}
}
}
System.out.println("8");
}
System.out.println("9");
// http://www.sohailaziz.com/2012/06/scheduling-activities-services-and.html
// https://dev.twitter.com/docs/api/1.1
// https://developers.google.com/appengine/docs/java/datastore/jdo/creatinggettinganddeletingdata?csw=1#Updating_an_Object
// http://en.wikibooks.org/wiki/Java_Persistence/Inheritance
}
and 6 is here:
private void addHistoryDeviceJPAToDs(List<HistoryDeviceJPA> list) {
System.out.println("6");
EntityManager em = EMF.get().createEntityManager();
try {
for (int i=0; i<list.size(); i++) {
System.out.println("=> " + i + " - " + list.get(i).toString());
em.getTransaction().begin();
em.persist(list.get(i));
em.getTransaction().commit();
}
} finally {
em.close();
}
}
after debug I found the problem is in this line:
List<HistoryDeviceJPA> dbList = (List<HistoryDeviceJPA>) q.getResultList();
if(dbList == null)
addHistoryDeviceJPAToDs(historyDeviceJPAList);
'dbList' is never null and it's size is 0 if there is nothing in datastore. That's why addHistoryDeviceJPAToDs method never invoked. By changing the code to following problem solved and local db created.
List<HistoryDeviceJPA> dbList = (List<HistoryDeviceJPA>) q.getResultList();
if(dbList == null)
return;
System.out.println("5");
// If there is no result (shows there is no record for that device)
if(dbList.size() == 0)
addHistoryDeviceJPAToDs(historyDeviceJPAList);
For other people who come across the same issue --
GAE will not create local_db.bin until you put data in the datastore. So if the file is not there, there is likely a bug in the application code.
I continue to get the (Could not find a part of the path 'C:\Users(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros) exception. The directory is there on the drive but im not sure why i continue to get this exception.
Extra6DestPath = "C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"
static void copyMacrosAndBitmaps(string ExtraSourcePath, string Extra6xDestPath )
{
//counter for total Macro count on network
int Count = 0;
//counter for total bitmap count on network
int iCount = 0;
//Get File information to use for copy
FileInfo[] macrosArray;
FileInfo[] iconArray;
//Get Directory information to use for copy
DirectoryInfo di = new DirectoryInfo(ExtraSourcePath);
DirectoryInfo diIcon = new DirectoryInfo(ExtraIconPath);
//set all macro paths as a string from directory into an array
macrosArray = di.GetFiles("*.ebm");
Count = macrosArray.Length;
//set all bitmaps from directory into an array
iconArray = diIcon.GetFiles("*.bmp");
iCount = iconArray.Length;
//copy macros into destination folder
if (Count == 0)
{
throw new FileNotFoundException("No Macros found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(Extra6xSourcePathW7 + macrosArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
//Copy the bitmaps into destination folder
if (iCount == 0)
{
throw new FileNotFoundException("No bitmaps found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(ExtraIconPath + iconArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
}
}
}
I would first try declaring the path with # symbol, to handle characters that need to be escaped:
Extra6DestPath = #"C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"