Error while moving directory if already exist in java - java

I am trying to move directory forcefully that means if already exist then overwrite without asking.
Code :
import java.io.IOException;
import java.lang.System;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class MoveDirectory {
private static void movefilesandfolder(String sourceFilevar,String destinationFilevar)
{
System.out.println("source="+sourceFilevar);
System.out.println("destination="+destinationFilevar);
Path sourceFile=Paths.get(sourceFilevar);
Path destinationFile=Paths.get(destinationFilevar);
try {
Files.move(sourceFile, destinationFile,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Sole entry point to the class and application.
* #param args Array of String arguments.
*/
public static void main(String[] args) {
movefilesandfolder("C:\\FTPDownload\\Downloaded\\epi141225_0001","C:\\FTPDownload\\In_Progress\\epi141225_0001");
}
}
Error output:
source=C:\FTPDownload\Downloaded\epi141225_0001
destination=C:\FTPDownload\In_Progress\epi141225_0001
java.nio.file.DirectoryNotEmptyException: C:\FTPDownload\In_Progress\epi141225_0001
at sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:372)
at sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:286)
at java.nio.file.Files.move(Files.java:1345)
at MoveDirectory.movefilesandfolder(MoveDirectory.java:22)
at MoveDirectory.main(MoveDirectory.java:36)
This code works if Folder not present on destination path but fails if already exist. This code doesn't work even if empty folder is present on destination path.
Files.move(sourceFile, destinationFile,StandardCopyOption.REPLACE_EXISTING);
In this call option i am using is not working for folder. This code Tested for file and it worked for already exist file as well.
But I want to move/overwrite folder.

You can delete destination directory before moving, or, if you want to merge directories together, loop your directory files and move anyone in new folder
System.out.println("source="+sourceFilevar);
System.out.println("destination="+destinationFilevar);
Path sourceFile=Paths.get(sourceFilevar);
Path destinationFile=Paths.get(destinationFilevar);
try {
if(new File(destinationFile).exists()){
// DELETE DIRECTORY
}
Files.move(sourceFile, destinationFile,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
or
System.out.println("source="+sourceFilevar);
System.out.println("destination="+destinationFilevar);
Path sourceFile=Paths.get(sourceFilevar);
Path destinationFile=Paths.get(destinationFilevar);
try {
if(new File(destinationFile).exists()){
// for each file in sourceFile
// Files.move file ...
}else{
Files.move(sourceFile, destinationFile,StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

javadoc:
public static Path move(Path source,
Path target,
CopyOption... options)
throws IOException
Move or rename a file to a target file.
By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory.

You can try using Path.resolve(other Path) method like this
Files.move(sourceFile, destinationFile.resolve(Paths.get(sourceFile).getFileName()), StandardCopyOption.REPLACE_EXISTING)
Java docs, give the best explanation about this.

Related

Updating resource files at runtime

When my application starts it reads a configuration properties file using the following code:
Properties properties = new Properties();
// parse the config resource
try (InputStream input = getClass().getClassLoader().getResourceAsStream(filename))
{
if (input == null)
{
// throw exception
}
// read the property list (key-value pairs) from the input byte stream
properties.load(input);
}
I am able to read and set individual properties.
The properties file is located in src/main/resources and after I build the application using maven, a copy of it is placed in target/classes. The jar file that is created also has a copy of it in the root directory when I open it up.
I would also like to be able to overwrite the properties file so that next time the application starts up, then it will read the new updated file. How do I achieve this? Is it even possible?
I found this question but no answers.
I've tried this:
try (OutputStream output = new FileOutputStream(filename))
{
properties.store(output, null);
}
which works if I just want to create a new file altogether. I would then have to modify the application so that it reads from a given folder rather than what originated from the resources folder. Is this what I should be doing?
I'm fairly new to Java so please go easy.
Storing the initial, default properties in the jar file, as resources is fine.
But if you want them to be writable, then you need to really store them as a file somewhere on the disk. Typically, under a .yourapp directory (or in a .yourapp file) inside the user's home directory.
So, try finding the file, and if not present, fallback to the resources. When writing, always write to the file.
This is an example code you can use for this. You create a config folder in the project root directory, an inside it you place your app.properties file
package com.yourparckage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Config {
/* Create basic object */
private ClassLoader objClassLoader = null;
private Properties commonProperties = new Properties();
public static final String CONFIG_FILE = "config/app.properties";
/**
* This method loads config data from properties file
*
*/
public Config() {
objClassLoader = getClass().getClassLoader();
}
public String readKey(String propertiesFilename, String key)
{
/* Simple validation */
if (propertiesFilename != null && !propertiesFilename.trim().isEmpty() && key != null
&& !key.trim().isEmpty()) {
/* Create an object of FileInputStream */
InputStream objFileInputStream = null;
/**
* Following try-catch is used to support upto 1.6. Use try-with-resource in JDK
* 1.7 or above
*/
try {
/* Read file from resources folder */
objFileInputStream = new FileInputStream(propertiesFilename);
/* Load file into commonProperties */
commonProperties.load(objFileInputStream);
/* Get the value of key */
return String.valueOf(commonProperties.get(key));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
/* Close the resource */
if (objFileInputStream != null) {
try {
objFileInputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
return null;
}
}

Java-simple-serial-connector trows exception UnsatisfiedLinkError

I downloaded the sources from here. This is the code with wich I am trying to open com port 13.
I saw in the device menager that com port13 is present.
import jssc.*;
public class Main {
static boolean s = false;
public static void main(String[] args) {
// TODO Auto-generated method stub
SerialPort ser = new SerialPort("COM1");
try {
s = ser.openPort();
} catch (SerialPortException e) {
// TODO Auto-generated catch block
System.out.println("Riko Stana neshto");
//e.printStackTrace();
}
//System.out.println("Riko" + ser.getPortName() );
}
}
When ran in Eclipse this appears in the console:
Exception in thread "main" java.lang.UnsatisfiedLinkError: jssc.SerialNativeInterface.openPort(Ljava/lang/String;Z)J
at jssc.SerialNativeInterface.openPort(Native Method)
at jssc.SerialPort.openPort(SerialPort.java:158)
at Main.main(Main.java:9)
The linbrary consist of java files and two dll file. I linked the java files to my eclipse project, but not sure how they are linked to the dll files. Should I do something in order to link the .java files to the .dll files? Could it be the cause of my problem? Any help is very much appreciated.
Download the JSSC zip here: https://code.google.com/archive/p/java-simple-serial-connector/downloads
Extract jssc.jar in your project folder.
Add the "jssc.jar" to your classpath as a .jar library.
Optional: Extract javadoc/jssc-2.7.0-javadoc.jar and javadoc/jssc-2.7.0-src.jar in your project folder and add them as javadoc and sources respectively.
Problem solved.
Edit - pitcure:

The below given code is returning null when I am loading the property file

The code sample given below returns null value.
Directory structure for your reference is :
D:\Postcard_workspace_new\Postcard_workspace\ConfigMigrationUtility\ConstantFiles ->contains the constants.properties file
D:\Postcard_workspace_new\Postcard_workspace\ConfigMigrationUtility\src\configmigrator\utility ->contains below given java class
Code :
public class PropertyUtil {
public static Properties prop;
public static Properties constantProp;
constantProp = new Properties();
public static void loadPropertyFile(String inputfilename) {
try {
// Loads the constants.properties file
InputStream constantPropFile = ClassLoader.class
.getResourceAsStream("/ConstantFiles/constants.properties");
System.out.println(constantPropFile);//prints null
constantProp.load(constantPropFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
log.equals("Constant Property file not found");
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
log.error("Can't Load constants.properties property
file ");
}
}
}
Place the file constants.properties at the following location:
D:\Postcard_workspace_new\Postcard_workspace\ConfigMigrationUtility\src
And access it using this:
InputStream constantPropFile = ClassLoader.class.getResourceAsStream("/constants.properties");
If you are working in eclipse then include that properties file's folder in src folder. Else just copy that properties file and paste in the src folder. Because At the runtime jvm finds the file in src folder.
if you add "ConstantFiles" folder to your project build path, you can access it using ClassLoader.class
.getResourceAsStream("/constants.properties");
(If you are using eclipse, right click on project > build path > configure build path > add folder on source tab)

Extracting Text From JPG

I've tried this code and added the needed jar files but still I'm getting an error message like Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'libtesseract302'.
Is there a complete tutorial how to extract text and what things should be done to address the error? Any help is appreciated...
import net.sourceforge.tess4j.*;
import java.io.File;
public class ExtractTxtFromImg {
public static void main(String[] args) {
File imgFile = new File("C:\\Documents and Settings\\rueca\\Desktop\\sampleImg.jpg");
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
try {
String result = instance.doOCR(imgFile);
System.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
In addition to adding the jars, you also need to add the natives. You can do so with Djava.library.path="C:\[absolute path to dir containing *.dll files and such]"
Note that you need to provide the directory, not the file itself.

Writing to a test file: Error within code?

Is there an error within the following code, It does not seem to be creating the text file (numbers.txt) that I am intending? I am aware that It is supossed to create the file in the JRE System library but I cannot locate it.
package test;
import java.io.FileNotFoundException;
import java.util.Formatter;
public class FileReaderTest {
private Formatter output;
/**
* default const
*/
public FileReaderTest() {
}
/**
* Method that enables a user to open a file
*/
public void openFile() {
try {
output = new Formatter("numbers.txt");
} catch (FileNotFoundException e) {
System.err.println("Problem found when opening file");
System.exit(1);// terminate
} catch (SecurityException Se) {
System.err.println("You dont have access to open file");
System.exit(1);// terminate
}
}// end of openFile
/**
* Method enabling user to write numbers to file
*/
public void writeToFile() {
// numbers to be written to file
Integer[] numbers = { 2, 5, 6, 7, 8, 9 };
for (Integer i : numbers) {
output.format("%d/n", i);
}
}// end of writeToFile
/**
* Method that closes file
*
*/
public void closeFile() {
if (output != null) {
output.close();
}
}// end of close file
}// class end
My implementation of the fileReaderTest in the Main:
public static void main(String[] args) {
//file input/putput testing
System.out.println("Opening file");
FileReaderTest file1= new FileReaderTest();
file1.openFile();//opening the file
file1.writeToFile();//writing values within the file
file1.closeFile();//closing the file
System.out.println("Finished with file");
}
}
I Think you should use File.getAbsolutePath()
On UNIX systems, a relative pathname is made absolute by resolving it against the current user directory. On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.
your current execution dir is: new File(".").getAbsolutePath(), check there

Categories

Resources