I am trying to copy a file form a folder to another folder
i have tried what was suggested in other posts but i have not been successful
Copying files from one directory to another in Java
this has not worked for me
the file is C:/Users/win7/Desktop/G1_S215075820014_T111_N20738-A_D2015-01-26_P_H0.xml
the destination folder is C:/Users/win7/Desktop/destiny
this is the copy code
String origen = "C:/Users/win7/Desktop/G1_S215075820014"
+"_T111_N20738-A_D2015-01-26_P_H0.xml";
String destino = "C:/Users/win7/Desktop/destiny";
private void copiarArchivoACarpeta(String origen, String destino) throws IOException {
Path FROM = Paths.get(origen);
Path TO = Paths.get(destino);
CopyOption[] options =
new CopyOption[] {StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES };
java.nio.file.Files.copy(FROM, TO, options);
}
Try:
java.nio.file.Files.copy(FROM, TO.resolve(FROM.getFileName()),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
Because the second parameter must be a Path to a file that not yet exists.
Just like the docu sais:
Related
I am trying to create a runnable jar file. My project includes models.txt file. My project works perfectly in eclipse with no error but when exported to a runnable jar file, It doesn't work. I hereby attach the error and the piece of code where the file is been called.
public static HashMap<String, RenderModel> getModelList(String file) throws IOException {
List<String> data;
HashMap<String, RenderModel> namesToModels = new HashMap<String, RenderModel>();
if (file != null) {
data = Files.readAllLines(Paths.get(file), StandardCharsets.UTF_8);
} else {
String path = "models/models.txt";
data = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
}
Iterator<String> dataIterator = data.iterator();
while (dataIterator.hasNext()) {
String dataLine = dataIterator.next();
System.out.println(dataLine);
String[] line = dataLine.split("; ");
String key = line[0];
String valueObj = line[1];
String valueMtl = line[2];
float scale = Float.parseFloat((String) line[3]);
RenderModel v = new RenderModel(valueObj, valueMtl, scale);
namesToModels.put(key, v);
}
RenderModel v = new RenderModel("custom", "custom", 1.0f);
namesToModels.put("Choose Model from file", v);
return namesToModels;
}
Error Image:
If the files are in the Jar and you cannot read them, try accessing the files by doing:
getClass().getClassLoader().getResource(fileName);
Use this instead for static methods:
ClassName.class.getClassLoader().getResource(fileName);
Where fileName is the name of the file and ClassName the name of the class from which the statement is called.
In your code the path of the model.txt is 'src/models/model.txt'. When your project is packaged the src folder is not included usually. Then you must change the file location; could be better put the file outside the jar, but inside the java classpath.
It does not work because you do not have any file on the path src/models/models.txt when you run your jar else where, this path is only present in your IDE (ofcourse you can place your jar in a location from where it can reach that path, but this is not how it is supposed to be), when you package your project into a jar file it is packed in the package models and you can if you want to have it as default file read it via classpath.
I am trying to create a method that searches inside a folder for .png files and returns a String array with the respective path to each file. It must look inside a resource folder placed NOT in the src, but in project.
The following code works when running from within Eclipse:
// Analyzes specified folder and returns a file array
// populated with the .png files found in that folder
private File[] imageReader(String filePath) {
File folder = new File(filePath);
return folder.listFiles (new FilenameFilter() {
public boolean accept(File filePath, String filename)
{ return filename.endsWith(".png"); }
});
}
// Converts the file array into a string array
private String[] listPngFiles(String filePath) {
File[] imagesFileArray = imageReader(filePath); // file array
String[] imagesStringArray = new String[imagesFileArray.length];
for(int i=0; i<imagesFileArray.length; i++) {
imagesStringArray[i] = "" + imagesFileArray[i];
imagesStringArray[i] = imagesStringArray[i].substring(6); // discards "/images" from directory string
}
return imagesStringArray;
}
However it is not working when I run the exported executable JAR file. This is my current project setup:
.
I have tried the following code but it did not work either:
ClassLoader classLoader = getClass().getClassLoader();
File folder = new File(classLoader.getResource(filePath).getFile());
The reason I am doing this is because I want to have a JButton display an icon chosen from one of the sub folders inside the images resource folder. My JButton already has the following code:
.setIcon(new ImageIcon(GameLogic.class.getResource(**insert listPngFiles array element here**)));
Your help on the matter would be greatly appreciated.
You can achieve this by using Reflections, take a look at getResources
trying to rename internal file within a zip file without having to extract and then re-zip programatically.
example. test.zip contains test.txt, i want to change it so that test.zip will contain newtest.txt(test.txt renamed to newtest.txt, contents remain the same)
came across this link that works but unfortunately it expects test.txt to exist on the system. In the example the srcfile should exist on the server.
Blockquote Rename file in zip with zip4j
Then icame across zipnote on Linux that does the trick but unfortunately the version i have doesnt work for files >4GB.
Any suggestions on how to accomplish this? prefereably in java.
This should be possible using Java 7 Zip FileSystem provider, something like:
// syntax defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/directoryPath/file.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap())) {
Path sourceURI = zipfs.getPath("/pathToDirectoryInsideZip/file.txt");
Path destinationURI = zipfs.getPath("/pathToDirectoryInsideZip/renamed.txt");
Files.move(sourceURI, destinationURI);
}
Using zip4j, I am modifying and re-writing the file headers inside of the central directory section to avoid rewriting the entire zip file:
ArrayList<FileHeader> FHs = (ArrayList<FileHeader>) zipFile.getFileHeaders();
FHs.get(0).setFileName("namename.mp4");
FHs.get(0).setFileNameLength("namename.mp4".getBytes("UTF-8").length);
zipFile.updateHeaders ();
//where updateHeaders is :
public void updateHeaders() throws ZipException, IOException {
checkZipModel();
if (this.zipModel == null) {
throw new ZipException("internal error: zip model is null");
}
if (Zip4jUtil.checkFileExists(file)) {
if (zipModel.isSplitArchive()) {
throw new ZipException("Zip file already exists. Zip file format does not allow updating split/spanned files");
}
}
long offset = zipModel.getEndCentralDirRecord().getOffsetOfStartOfCentralDir();
HeaderWriter headerWriter = new HeaderWriter();
SplitOutputStream splitOutputStream = new SplitOutputStream(new File(zipModel.getZipFile()), -1);
splitOutputStream.seek(offset);
headerWriter.finalizeZipFile(zipModel, splitOutputStream);
splitOutputStream.close();
}
The name field in the local file header section remains unchanged, so there will be a mismatch exception in this library.
It's tricky but maybe problematic, I don't know..
I'm having the following code in my mapper [ Hadoop - Map Reduce ]
Im trying to create a folder in the shared path
protected void setup(Context context)
throws IOException,InterruptedException
{
fileName1 = ((FileSplit) context.getInputSplit()).getPath().getName().toString();
Directory = "\\\\DEV144\\MapperFile\\"+fileName1;
File directory1 = new File(Directory);
if (!directory1.exists())
{
boolean result = new File(Directory).mkdirs();
System.out.println(Directory);
if(result)
{
System.out.println("DIR created");
System.out.println(Directory);
}
}
mos = new MultipleOutputs(context);
above code is not creating the folder. But when i give something like this
Directory = "E:\\MapperFile\\"+fileName1;
File directory1 = new File(Directory);
And point the local system it is creating Folder and working fine
My question is why it is not able to create folder in the shared path ?
And what is wrong in my code
I had a similar problem and I start using jCIFS. I have to point out that this was used to access windows shared directory from a linux machine. For creating directory you can use:
String smbUrl = "smb://domain;username:password#server/share/myNewDirectory";
SmbFile smbFile = new SmbFile(smbURL);
try{
smbFile.mkdir();
}catch(SmbException e){...}
And don't forget to check if you have sufficient permissions for a java application.
int reval = fcCari.showOpenDialog(this);
String sourcePath = fcCari.getSelectedFile().getAbsolutePath();
String targetPath = "C:\\Users\\nadzar\\Downloads\\Compressed\\JavaSQLite\\resource\\";
targetPath += fcCari.getSelectedFile().getName();
if ((reval == JFileChooser.APPROVE_OPTION)) {
File source = new File(sourcePath);
File target = new File(targetPath);
copyFile(source, target);
targetPathFoto=targetPath;
tambahFoto(targetPathFoto);
}
else{
JOptionPane.showMessageDialog(rootPane, "Batal Menambahkan Foto");
tambahFoto(this.targetFoto);
}
System.out.println(targetPathFoto);
If my project has moved, the path must be changed.
I ask how can the target path change while my project directory has changed?
Use properties file for this purpose, what you need to do is change the property value.
# app home, build absolute paths in code using this path
app.home=path_to_home_directory
Use java.util.Properties to read these properties.
See examples at mkyong.