Just for kicks I was experimenting and trying to make a program that would move all the files from my D:\Downloads directory that were installers to my G:\Downloads\Installers directory. I thought I had it working but upon using it, it returns "The process cannot access the file because it is being used by another process."
Here is the code and any input would be appreciated.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class FileOrganizer {
public static void main(String[] args) {
File folder = new File("d:/Downloads");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String name = listOfFiles[i].getName();
if (name.indexOf("Setup") > -1) {
Path source = Paths.get("d:/Downloads");
Path target = Paths.get("g:/Downloads/Installers");
try {
Files.move(source,
target.resolve(source.getFileName())),
StandardCopyOption.REPLACE_EXISTING);}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
Thanks in advance!
Try to change file name of each file, if file name is changeable then file is not used by any other process. You can not trace it with eyes, because there can be any thread which use it. After check each file, move it.
File sourceFile = ...;
boolean changeableSource = source.renameTo(sourceFile);
File destFile = ...;
boolean changeableSource = destFile.renameTo(destFile);
if(changeableSource && changeableSource ){
//Moving here...
}
Related
I'm having real difficulties figuring out how this needs to be coded without using FileUtils import. I have found thousands of tutorials on how to move files to empty folders, that's easy. The difficulty is finding out how Java can move files to directories that already have files in the folder. As I understand it the REPLACE_EXISTING parameter means it will overwrite identical file names if detected in the destination directory, but the directory doesn't have a file with a matching name of the file I'm attempting to copy/move. What am I missing? How can I make this happen?
java.nio.file.DirectoryNotEmptyException occuring.
enter code here
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Move {
static File source = new File("sourcefolderhere");
static File destination = new File("destfolderhere");
public static void move(File src, File dest) throws IOException {
Files.move(src.toPath().toAbsolutePath(), dest.toPath().toAbsolutePath(),
StandardCopyOption.REPLACE_EXISTING);
}
public static void main(String[] args) throws IOException {
try {
if(source.isDirectory() && destination.isDirectory()) {
File[] content = source.listFiles();
for(int i = 0; i < content.length; i++) {
System.out.println(content[i]);
move(source, destination);
}
}
else if (!destination.isDirectory()){
System.out.println("create folder here");
destination.mkdir();
File[] content = source.listFiles();
for(int i = 0; i < content.length; i++) {
move(source, destination);
}
}
}
catch(Exception ex) { System.out.println(ex);
}
finally {
}
}
}
I tried the code in IDE File.move method with parameter StandardCopyOption.REPLACE_EXISTING works only if you have file in the destination folder. otherwise use File.move the normal way. I have also modified your code a little just to avoid code duplication.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
public class Move {
static File source = new File("sourcefolderhere");
static File destination = new File("destfolderhere");
public static void move(File src, File dest) throws IOException {
System.out.println(src.getName());
if(isExist(src.getName()))
Files.move(src.toPath().toAbsolutePath(), Paths.get(destination.getAbsolutePath()+File.separator+src.getName()) , StandardCopyOption.REPLACE_EXISTING);
else
Files.move(src.toPath().toAbsolutePath(), Paths.get(destination.getAbsolutePath()+File.separator+src.getName()));
}
public static boolean isExist(String souceFileName){
//If you are not using java 8 code
/*String[] destFiles = destination.list();
for(String fileName : destFiles){
if(souceFileName.equals(fileName))
return true;
}
return false;*/
return Arrays.stream(destination.list())
.anyMatch(fileName -> fileName.equals(souceFileName));
}
public static void main(String[] args) throws IOException {
try {
if(!source.isDirectory())
throw new IllegalArgumentException("Source Folder doesn't Exist");
if(!destination.exists())
destination.mkdir();
if (source.isDirectory() && destination.isDirectory()) {
File[] content = source.listFiles();
for (int i = 0; i < content.length; i++) {
System.out.println(content[i]);
move(content[i], destination);
}
}
} catch (Exception ex) {
System.out.println(ex);
} finally {
}
}
}```
I have most of it down but when I try to make the copy, no copy is made.
It finds the files in the specified directory like it is supposed to do and I think the copy function executes but there aren't any more files in the specified directory. Any help is appreciated. I made a printf function that isn't shown here. Thanks!
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Scanner;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.FileUtils;
import static java.nio.file.StandardCopyOption.*;
public class Stuff {
static String path, oldExtn, newExtn;
static Boolean delOrig = false;
private static void getPathStuff() {
printf("Please enter the desired path\n");
Scanner in = new Scanner(System.in);
path = in.next();
printf("Now enter the file extension to replace\n");
oldExtn = in.next();
printf("Now enter the file extension to replace with\n");
newExtn = in.next();
in.close();
}
public static void main(String[] args) {
getPathStuff();
File folder = new File(path);
printf("folder = %s\n", folder.getPath());
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.getName().endsWith(oldExtn)) {
printf(fileEntry.getName() + "\n");
File newFile = new File(FilenameUtils.getBaseName(fileEntry
.getName() + newExtn));
try {
printf("fileEntry = %s\n", fileEntry.toPath().toString());
Files.copy(fileEntry.toPath(), newFile.toPath(),
REPLACE_EXISTING);
} catch (IOException e) {
System.err.printf("Exception");
}
}
}
}
}`
The problem is that the new file is created without a full path (only the file name). So your new file is created - only not where you expect...
You can see that it'll work if you'll replace:
File newFile = new File(FilenameUtils.getBaseName(fileEntry
.getName() + newExtn));
with:
File newFile = new File(fileEntry.getAbsolutePath()
.substring(0,
fileEntry.getAbsolutePath()
.lastIndexOf(".")+1) + newExtn);
I want to compare file lying in two different folders.
I wish to compare only files which have same name in those two different folders.
What I wish to do is to compare two different versions of a software and find how many files have been changed.
This will help you get files for two paths:
import java.io.File;
import java.util.*;
public class ListFiles
{
public static void main(String[] args)
{
// First directory path here.
String path1 = ".";
// Second directory path here.
String path2 = ".";
// File class is very important.
// If you did a simple Google search
// Then you would have seen this class mentioned.
File folder1 = new File(path1);
File folder2 = new File(path2);
// It gets the list of files for you.
File[] listOfFiles1 = folder1.listFiles();
File[] listOfFiles2 = folder2.listFiles();
// We'll need these to store the file names as Strings.
ArrayList<String> fileNames1 = new ArrayList<String>();
ArrayList<String> fileNames2 = new ArrayList<String>();
// Get file names from first directory.
for (int i = 0; i < listOfFiles1.length; i++)
{
if (listOfFiles1[i].isFile())
{
fileNames1.add(listOfFiles1[i].getName());
}
}
// Get file names from second directory.
for (int i = 0; i < listOfFiles2.length; i++)
{
if (listOfFiles2[i].isFile())
{
fileNames2.add(listOfFiles2[i].getName());
}
}
// Now compare
// Loop through the two array lists and add your own logic.
}
}
You will need to add your own logic to compare. Source
I have this code which compares all the files in the directory with a particular file to check if that files aleady exists in the directory,may tweak that a little as per your needs.It uses commons-io.jar
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
public class CompareFile {
String directory;
File file;
public CompareFile(String directory, File file) {
this.directory = directory;
this.file = file;
}
public boolean doesFileExist() {
boolean indicatorFileExist = true;
List<File> files = null;
try {
files = getFiles();
files = files.stream().filter(fileMatch -> {
try {
if(fileMatch.isFile()){
return FileUtils.contentEquals(fileMatch, file);
}else{
return false;
}
} catch (Exception excep) {
excep.printStackTrace();
return false;
}
}).collect(Collectors.toList());
if(files.isEmpty()){
indicatorFileExist = false;
}
} catch (Exception excep) {
excep.printStackTrace();
} finally {
if (files != null) {
files = null;
}
}
return indicatorFileExist;
}
private List<File> getFiles() {
List<File> fileList = null;
try {
if(directory!=null && directory.trim().length()>0 && file!=null){
File dir = new File(directory);
if(dir.isDirectory() && dir.exists() && dir.canRead()){
fileList = Arrays.asList(dir.listFiles());
}
}
} catch (Exception excep) {
excep.printStackTrace();
}
return fileList;
}
}
I need to make a menu that list the .txt files in a directory. For example, if i have jonsmith12.txt , lenovo123.txt , dell123.txt in the directory how would I make an arraylist menu of:
Please choose one of the following:
jonsmith12
lenovo123
dell123
Please enter your choice:
I need an arraylist menu is because I don't know how many .txt files are in the directory at any given time.
import java.io.File;
public class ListFiles
{
public static void listRecord() {
// Directory path here
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
System.out.println(files);
}
}
}
}
}
Here is the class that will display the information in the .txt file onto the console. It stills need some modifying too but I could probably figure that out.
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* This program reads a text file line by line and print to the console. It uses
* FileOutputStream to read the file.
*
*/
public class DisplayRec {
public static void displayRecord() throws IOException {
File file = new File("williamguo5.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(dis.readLine());
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
So the question is: How do I implement a ArrayList menu into my ListFiles class so it will display the .txt files.
You can use the alternate method signature for File.listFiles(FilenameFilter filter) to simplify your code:
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
And unless you really enjoy writing loops, you don't even need to manually loop over the array to convert it to a List:
List<File> lstRecords = Arrays.asList(files);
Your displayRecord method was pretty close; you just needed to pass the file as an argument and use that instead of a hard-coded filename, and you needed to initialize dis.
Putting it all together:
package com.example.file;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class FileExample {
public static List<File> listRecords(File dir) {
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
return Arrays.asList(files);
}
public static void displayRecord(File file) {
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
String line = dis.readLine();
while (line != null) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(line);
line = dis.readLine();
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
List<File> lstRecords = listRecords(new File("."));
for (File record : lstRecords) {
displayRecord(record);
}
}
}
It's also better to use Reader/Writer instead of InputStream/OutputStream if you're working with text files, and you should close your files in the finally block to avoid a potential resource leak.
You'll also notice I didn't explicitly use an ArrayList. In most cases, it's better to program against the interface (in this case, List) as much as possible, and only declare variables using the implementing class when you need to use a method that's only available to that class.
It looks like your sticking point above is the array. If you just need to iterate over the files in a directory, something as simple as the following will do the trick.
import java.io.File;
public class TxtEnumerator {
public static void main(String[] args) {
TxtEnumerator te = new TxtEnumerator();
te.listFiles();
}
public void listFiles() {
String filepath = "." + File.separator + "textDirectory";
File file = new File(filepath);
if (file.isDirectory()) {
for (File f : file.listFiles()) {
if (f.getName().endsWith(".txt")) {
System.out.println(f.getName());
}
}
}
}
}
I'm having a problem where I can't find images through Java. My friend and I are working on a project and we've done the exact same things. I've changed the paths to the location of the images and even dragged/dropped the images into Eclipse. However, I've had no luck. Here's my code:
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MapArray {
static JPanel[][] tiles = new JPanel[30][29];
static String[][] images = new String[30][30];
final static int SIZE = 30;
static int place=0;
public MapArray(){
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Map.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void setMap(){
try {
String a = getFileContents("C:\\Users\\*****\\workspace\\Pokemon\\src\\map1.txt");
for(int x=0; x<29; x++){
for(int y=0; y<30; y++){
images[x][y]=a.substring(0,a.indexOf(" "));
a=a.substring(a.indexOf(" ")+1);
System.out.println(images[x][y]);
}
}
} catch (Exception e) {
System.out.println("y u no work :(");
}
}
public static String getFileContents(String fileName) throws Exception {
File theFile = new File(fileName);
byte[] bytes = new byte[(int) theFile.length()];
InputStream in = new FileInputStream(theFile);
int m = 0, n = 0;
while (m < bytes.length) {
n = in.read(bytes, m, bytes.length - m);
m += n;
}
in.close();
return new String(bytes);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
setMap();
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(30, 29, 0, 0));
for (int i = 0; i < 29; i++) {
for (int j = 0; j < 29; j++) {
tiles[i][j] = new JPanel(new GridLayout());
tiles[i][j].add(new JLabel(
createImageIcon("C:\\Users\\*****\\workspace\\Pokemon\\src\\tile"+"-"+images[i][j]+".png")));
frame.add(tiles[i][j]);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
Everything I've tried with putting in the full image path doesn't work. Also, would anyone be able to help with relative paths? My friend and I will be sharing code between multiple computers so relative paths that aren't dedicated on where our workspace is located would be great. Thanks!
// get resource of *your* class, instead of Java's Map.class
MapArray.class.getResource(path);
...
String a = getFileContents("map1.txt"); // local path, not absolute
and put the file to your src folder, next to the MapArray.java file.
src/
|-- MapArray.java
|-- ...
`-- map1.txt
map1.txt will be moved into bin directory, next to .class file (bin/ is hidden in Eclipse by default, but that's where the classpath is set). Later you'll also want to make sure that the resource file is packaged into .jar.
would anyone be able to help with relative paths?
String a = getFileContents("./src/map1.txt");
Instead of posting a a whole bunch of code and not specifying the error message you get in your question, you could start with a simple code snippet (I neglect imports, ... since I am too lazy to fire up my IDE)
public static void main( String[] args ){
File file = new File( "C:...");//with the path you use in your code
System.out.println( file.exists() );
}
This is about what you need to discover/debug your problem. Then you can start on converting it to a relative path.
If the resources are inherently part of the app. (an embedded application resource) and not for write, they should be added to a Jar on the application's run-time class-path and accessed via URL obtained from Class.getResource(). It would work something like:
URL urlToMap1 = this.getClass().getResource("/src/map1.txt");
You'd need to check the exact path in the Jar that resource ends up at, and reference it from the root of the Jar (/) then the path within the Jar (src/map1.txt).