How to move specific files from one folder to another using java - java

I have tried and succeed moving files from one folder to another folder using java . Here is my code
File source = new File("D:\\polo\\");
File desc = new File("E:\\polo2\\");
try {
FileUtils.copyDirectory(source, desc);
} catch (IOException e) {
e.printStackTrace();
}
But i would like to move specific files from one folder to the other not all the files. Is this possible to do in java. Please help us on this

You can use Java SE standard utility
java.nio.file.Files.copy(Path source, Path target, CopyOption... options)

use renameTo
public static void main(String[] args)
{
try{
File source = new File("D:\\polo\\");
File desc = new File("E:\\polo2\\");
if(source .renameTo(new File("E:\\polo2\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}

In java 1.7, new IO classes were added, including the Files utility class which has a method copy.
There is an example of usage here.

Use IOUtils Library for copy file from one location to another location.
For eg.
File source = new File("D:\\polo\\fileold");
File desc = new File("E:\\polo2\\filenew");
IOUtils.copy(source, desc);
Try this..

Related

Is there a way to replace an html file with another one by coding in Java?

My purpose is to replace an html file in a folder by another one, so that at the end :
html_link1 will be replaced by html_link2
Is there a way to update HTML files by executing code in Java ?
public static void main(String[] args) {
Path sourceDirectory = Paths.get("C:/Users/Me/Desktop/project/adresse.url");
Path targetDirectory = Paths.get("C:/Users/Me/Desktop/project/adresse2.url");
//copy source to target using Files Class
try {
Files.copy(sourceDirectory, targetDirectory,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
I need to find a way to change the URL, since the Path are now the same, the URL of the second HTML file didn't changed
You have to pass the absolute file path untill and unless you wish to replace the whole directory.
Path sourceFilePath = Paths.get("C:/Users/Me/Desktop/project/adresse.url");
Path targetFilePath = Paths.get("C:/Users/Me/Desktop/project/adresse2.url");
try {
Files.copy(sourceFilePath , targetFilePath ,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.out.println(e.toString());
}
So long as they actually files, and you have the proper permission for the directory they are in, then you can do this the same way you would for any file.

FileNotFoundException coming from Java web application

I am working on the web application with Eclipse. I have created one property file for database configuration. (DBProperty.properties)
Please find below screen-shot of the folder structure.
I want to access this property file. I am accessing with below code.
FileInputStream input = new FileInputStream("src/resources/DBProperty.properties");
I have also tried many relative paths but not able to succeed.
I have set build path for this project.
You need to use
MyClass.class.getClassLoader().getResourceAsStream("DBProperty.properties")
FileInputStream input = new FileInputStream("resources/DBProperty.properties");
Please try the above line of code. Hope it will solve your problem.
The src directory isn't there at runtime.
Resources are not files.
You need to look into Class.getResource() and friends.
You have to specify complete file path with File object.
public static void main(String[] args) {
File file = new File("C:\\Path\\workspace\\jbossmqimpl\\Test1\\resources\\NewFile.xml");
try (FileInputStream fis = new FileInputStream(file)) {
System.out.println("Total file size to read (in bytes) : "+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
}

URI not hierarchical need to use File class for a method

I need to open a video file with my code, and it works perfectly fine in Eclipse but when I export into a runnable JAR, i get an error "URI not hierarchical".
I have seen people suggest using getResourceAsStream(), but i need to have a file object as i am using Desktop.getDesktop.open(File). Can anyone help me out?
Here is the code:
try {
URI path1 = getClass().getResource("/videos/tutorialVid1.mp4").toURI();
File f = new File(path1);
Desktop.getDesktop().open(f);
} catch (Exception e) {
e.printStackTrace();
}
if it helps my folder list is like
Src
videos
videoFile.mp4
EDIT:
I plan to run this on windows only, and use launch4j to create an exe.
You can copy the file from the jar to a temporary file and open that.
Here's a method to create a temporary file for a given jar resource:
public static File createTempFile(String path) {
String[] parts = path.split("/");
File f = File.createTempFile(parts[parts.length - 1], ".tmp");
f.deleteOnExit();
try (Inputstream in = getClass().getResourceAsStream(path)) {
Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
return f;
}
And here's an example of how you'd use it:
Desktop.getDesktop().open(createTempFile("/videos/tutorialVid1.mp4"));

Copying file without creating a FileOutputStream

I am making an application that includes file copying, but when I go through a large directory (1000+) files and copy them to another folder, it uses 290+ MB of RAM.
So, is there any way to change the File of FileOutputStream without creating a new instance of the FileOutoutStream class?
EDIT:
Here is my Java 7 API version.
Path source = FileSystems.getDefault().getPath(Drive.getAbsolutePath(), files[i].getName());
Path destination = FileSystems.getDefault().getPath(Save);
try {
Files.copy(source, destination);
} catch (FileAlreadyExistsException e) {
File file = new File(Save + files[i]);
file.delete();
}
Keep in mind, that this is in a for loop that is being tested on 1000+ file counts.
With the current method I am using 270+ MB of RAM
No, you can't redirect a FileOutputStream to a different file.
If you're using Java 7, you can use the new Files class to copy files. The Files.copy() methods can do most of the work for you.
Otherwise, verify that you're closing your streams. Prior to Java 7's try-with-resources, it could look something like this:
FileOutputStream out = null;
try {
// Create the output stream
// Copy the file
} catch (IOException e) {
// Do something
} finally {
if ( null != out ) {
try { out.close(); } catch ( IOException ) { }
}
}
Have a look at this question: Standard concise way to copy a file in Java?
specifically
..., Apache Commons IO is the way to go, specifically FileUtils.copyFile(); it handles all the heavy lifting for you.
How about some nio2 from Java 7?
Path source = // ...
Path target = // ...
Files.copy(source, target);
See javadoc of Files.copy(...) for details. See also the optional parameter CopyOption.

use java to create file in JavaScript

First of all I am iMacros scripts writer.
This is java function for writing a file (not fully complete but you will get the idea)
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.write("Writing line one to file");
Now bellow is java function used in JavaScript to do the same task as the function above and I run that .js file in iMacros. Works like a charm.
//Function to write the file
function writeFile(filename, data)
{
try
{
//write the data
out = new java.io.BufferedWriter(new java.io.FileWriter(filename, true));
out.newLine();
out.write(data);
out.close();
out=null;
}
catch(e) //catch and report any errors
{
alert(""+e);
}
}
Now I need a java function that will create file and folder on Hard Drive location and I found this.
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main( String[] args )
{
try {
File file = new File("c:\\newfile.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
But now I need java function that will create folder and an empty file (with different extensions like .txt .csv etc.) and the function will work in JavaScript.
Can anyone give me some guide lines from the two examples above? How can I write a functions in Java and run it in JavaScript?
I won't claim to fully understand the question, but this is how to make sure some directory exists, and to create a random file in it:
// make the dir and ensure the entire path exists
File destinationDir = new File("c:\\whereever\you\want\that\file\to\land").mkdirs();
// make some file in that directory
File file = new File(destinationDir,"whateverfilename.whateverextension");
// continue with your code
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
This function is used in iMacros .js file. It is a Java method called in JavaScript.
createFile("C:\\testingfolder","test.csv");
function createFile(folder,file)
{
destinationDir = new java.io.File(folder).mkdirs();
file = new java.io.File(folder,file);
file.createNewFile();
}
The function creates folder and in it creates a file.

Categories