Everyone keeps saying how simple it is to move a file from point a to point b using fileutils, but I'm having lots of trouble moving a file :(
I have a /temp/ folder in the directory wherever the .jar is located, in this temp folder I have a .txt file I want to move up a directory (so basically next to the .jar file) but I cant seem to do it?
Here's some code, but I know its not even close:
public void replaceFile() {
String absolutePath = getPath();
Path from = Paths.get(absolutePath + "\\temp\\test.txt");
Path to = Paths.get(absolutePath + "\\test.txt");
try {
FileUtils.moveFile(FileUtils.getFile(from.toAbsolutePath().toString()), FileUtils.getFile(to.toAbsolutePath().toString()));
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getPath() {
File jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath());
//JOptionPane.showMessageDialog(null, jarDir.getAbsolutePath());
return jarDir.getAbsolutePath();
}
Any help is appreciated :\
Why don't use this Java API for Moving a File or Directory
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
UPDATE
Looking at your source code I suggest the following implementation:
Path from = Paths.get(absolutePath, "/temp/test.txt");
Path to = Paths.get(absolutePath, "/test.txt");
try {
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ok i managed to do it, apparently the getPath() method returned some funny path and it failed there, so heres a code that works
public void downloadJar() {
String absolutePath = getPath();
String from = absolutePath + "\\temp\\test.txt";
String to = absolutePath + "\\test.txt";
File fileTo = new File(to);
File fileFrom = new File(from);
try {
FileUtils.moveFile(fileFrom, fileTo);
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "io exce");
}
}
public String getPath() {
return System.getProperty("user.dir");
}
thanks everyone
Related
I'm having a problem with opening file using PDFViewer library.
Inside DocumentCreator class:
1. First I create the document using iText library and it works perfectly fine and it writes document to the given directory.
2. Then I create an object of a File to display it using PDFViewer.
try {
mDocument = new Document(); // new Document created
String path = "/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + "-" + recipe.getTitle() + ".pdf";
String fullPath = Environment.getExternalStorageDirectory() + "/recipes" + path;
mPdfWriter = PdfWriter.getInstance(mDocument, new FileOutputStream(fullPath));
doTheWriting(recipe, activity);
Log.d("OK", "done");
mMyRecipeFile = new File(fullPath);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Inside same class (DocumentCreator) I created getter method for mMyRecipeFile.
public File getRecipeFile() {
return mMyRecipeFile;
}
After that in the DocumentTestFragment,
I created PDFView, called mPdfView, and I try to open this file.
mPdfView.fromFile(mDocCreator.getRecipeFile());
The problem is it is displaying an empty document, which is weird, because I opened Android Device Monitor, opened given file and it's not empty.
I found out what caused a problem. The thing is that I wrote:
PdfView.fromFile(file)
While proper form is
PdfView.fromFile(file).load();
It works just fine now.
I'm designing JMeter scenario which implies executing a certain .jar file via OS Process Sampler element. My Java code has while loop which basically checks a certain mailbox for a letter with a certain subject. Loop waits until finds one (emails are always delivered with roughly 3 minutes delay), parses it and writes some data to .txt file.
If I run this .jar directly from cmd then the code works as expected. But if I run it via JMeter OS Process Sampler then it never creates a file for me. I do see that email is delivered to inbox, so expect it to be parsed and .txt created.
At first I suspected that JMeter finishes Java scenario without waiting for while loop to execute. Then I put OS Process Sampler in a separate Thread and added a huge delay for this thread in order to wait and make 100% sure that email is delivered and Java only need to parse it but it does not help.
View Results Tree never shows any errors.
Here is my OS Process Sampler: https://www.screencast.com/t/LomYGShJHAkS
This is what I execute via cmd and it works as expected: java -jar mailosaurJavaRun.jar email533.druzey1a#mailosaur.in
And here is my code (it does not looks good but it works):
public class Run {
public static void main(String[] args) {
MailosaurHelper ms = new MailosaurHelper();
String arg1 = ms.getFirstLinkInEmail(args[0]);
BufferedWriter output = null;
try {
File file = new File("url.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(arg1);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class MailosaurHelper {
protected final String API_KEY = "b3e4d2b193b5eb2";
protected final String MAILBOX_ID = "d1uzey1a";
public MailboxApi getEmailBox() {
return new MailboxApi(MAILBOX_ID, API_KEY);
}
public String getFirstLinkInEmail(String email) {
MailosaurHelper ms = new MailosaurHelper();
String link = "";
if (link.equals("") || link.isEmpty()) {
try {
Thread.sleep(3000);
link = ms.getAllEmailsByReceipent(email)[0].html.links[0]
.toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return link;
}
public Email[] getAllEmailsByReceipent(String recepient) {
try {
int ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(recepient).length;
while (ifArrayIsEmpty == 0) {
try {
Thread.sleep(3000);
ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(
recepient).length;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (MailosaurException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Email[] listOfEmails = null;
try {
listOfEmails = getEmailBox().getEmailsByRecipient(recepient);
} catch (MailosaurException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listOfEmails;
}
The bottom line is that I need to parse Mailosaur email, retrieve URL from it and use it further. Any other suggestion on how to do that using Jmeter/Java/Mailosaur are appreciated.
You don't need cmd in here, but if you're adamant to stick with it - use /C key when you call it.
Then, are your sure you're looking for your file in the right place?
According to documentation:
By default the classes in the java.io package always resolve relative
pathnames against the current user directory. This directory is named
by the system property user.dir, and is typically the directory in
which the Java virtual machine was invoked.
Check it thoroughly, BTW - you should see it in your sampler result.
Trying to create and write to a file, but i get a FileNotFoundException every time, here is the method i am using:
public void saveFileAsPRN(Context context){
byte[] dataFile = getPrintableFileData();
String filename = "TestPrn.prn";
// instantiate a file object using the path
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
Log.e(TAG, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
//determine if the media is mounted with read & write access
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(TAG, "media mounted"); //good
}else{
Log.e(TAG, "media NOT mounted"); //bad
}
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
// determine if the file exists, create it if it does not
if(!file.exists()){
try {
Log.e(TAG, "File does not exist, creating..");
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.e(TAG, "File Exists");
}
//this makes the blank file visible in the file browser
MediaScannerConnection.scanFile(context, new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + filename}, null, null);
//create output stream - send data; saving to file
OutputStream out = null;
try {
FileOutputStream fos = null;
fos = new FileOutputStream(file); // <---- CRASHES HERE; FileNotFoundException
out = new BufferedOutputStream(fos);
out.write(dataFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A FileNotFoundException is raised on the following line:
fos = new FileOutputStream(file); // <---- CRASHES HERE;
The directory Exists, and a blank file is created in the target directory (visible by browsing target folder on PC).
Calling the method canWrite() on the File object returns true - i have write access.
The manifest contains: android.permission.WRITE_EXTERNAL_STORAGE"
So i'm out of ideas, i see several people have similar issues, but i cant find an answer.
Commenting out the following code fixed the issue:
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
that code does create a blank file, you can see it contained in the folder,
BUT - it's very misleading; you can't do anything with this file, i tried transferring it from my device to my PC and i couldn't, i also cannot open it. and you cannot open a stream to it in code.
Try this may helps you.
Replace this line
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
With
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), filename);
I have the problem, that I create a new file in a Java program, but I always get an exception, that the new created file is not local, when I try to open it on the eclipse project explorer view.
The code where I create it is as follows:
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IProject project = workspaceRoot.getProject(projectName);
FileUtil myFile = new FileUtil();
if (!project.getFile(FILE_NAME).exists()) {
IFile newFile = project.getFile("conf.txt");
FileInputStream fileStream = null;
try {
String temp = project + "/conf.txt";
temp = temp.substring(2);
fileStream = new FileInputStream(temp);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
newFile.create(fileStream, false, null);
} catch (CoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// create closes the file stream, so no worries.
try {
myFile.writeTextFile(FILE_NAME, "Seconds", output);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
FileUtil is a class which only implements the methods write and read for the file.
The Exception I get when I try to open it begins with:
org.eclipse.core.internal.resources.ResourceException: Resource '/ProjectE1/conf.txt' is not local.
at org.eclipse.core.internal.resources.Resource.checkLocal(Resource.java:353)
at org.eclipse.core.internal.resources.File.getContentDescription(File.java:264)
at org.eclipse.core.internal.propertytester.FilePropertyTester.testContentType(FilePropertyTester.java:108)
I somehow have to get a relative path during the runtime. Because I am opening a new instance of eclipse in the program, where I can see the Project in the Project Explorer but can't open the conf.txt file because it is not local.
It looks like your resource is an absolute path to /ProjectE1/conf.txt, I'm confused why you are not using java.io.
This will help you understand relative paths, I think this may be where you are wanting to put your conf file.
File file = new File("conf.txt");
if(!file.createNewFile()){
//err
}
System.out.println(file.getAbsolutePath());
I had similar issue. This is how I fixed.
First created file in local file system (using java.io)
Did project refresh
Reload the file
File file = new File(project.getWorkspace().getRoot().getLocation() + project.getFullPath().toString() + "/relative_path_of_my_file");
file.createNewFile();
project.refreshLocal(IProject.DEPTH_INFINITE, null);
keywordFile = project.getFile("/relative_path_of_my_file");
I get the following exception when trying to create a file on windows 7 using Java. An example of a path is "C:/g-ecx/images-amazon/com/images/G/01/gno/images/orangeBlue/navPackedSprites-US-22.V183711641.png". If I hard code in a path it does work however. I've been banging my head for two hours, can anyone help.
mkdir fails but doesn't through an exception, create file throws the exception.
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processImage(ImageProcessingBehavior.java:125)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.loadImages(ImageProcessingBehavior.java:99)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processNodes(ImageProcessingBehavior.java:66)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processRootNode(ImageProcessingBehavior.java:34)
at org.willmanning.mtt.html.ParsingFacade.processURL(ParsingFacade.java:38)
at org.willmanning.mtt.App.main(App.java:45)
/**
*
* #param image
* #param url
*/
public void processImage(BufferedImage image, URL url) {
StringBuilder path = new StringBuilder();
path.append("C:/Users/will/Documents/");
path.append(url.getHost().replace('.', '/'));
path.append(url.getFile());
path.replace(path.lastIndexOf("."), path.length(), ".txt");
File file = new File(path.toString());
boolean mkdir = file.mkdir();
boolean isNew = false;
try {
isNew = file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/*
* only create the file if it doesn't exist
*/
if (isNew) {
try {
ImageIO.write(image, "jpg", file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try using
boolean mkdir = file.mkdirs();
instead of
boolean mkdir = file.mkdir();
mkdirs() creates the whole parent path/directories if needed: