Trying to copy file and getting 'file does not exist' error - java

I am trying to copy files from 1 directory to another after re-naming them but keep getting the error:
Exception in thread "main" java.nio.file.NoSuchFileException: C:\Users\talain\Desktop\marketingOriginal\FX Rates\FY17\Q11\Week_12___February_12_2016.xls -> C:\Users\talain\Desktop\fakeOnedrive\FX Rates\FY17\Q11\0
My code:
public class shortenFilenameClass
{
static String absolutePathLocal = "C:\\Users\\talain\\Desktop\\marketingOriginal".replace('\\', '/'); //path to original files
static String absolutePathOnedrive= "C:\\Users\\talain\\Desktop\\fakeOnedrive".replace('\\', '/'); //path to onedrive
public static void main(String[] args) throws IOException
{
System.out.println(absolutePathLocal.length());
File local = new File(absolutePathLocal);
File onedrive = new File(absolutePathOnedrive);
int fileCount = 0;
File[] filesInDir = local.listFiles();
manipulateFiles(filesInDir, fileCount);
}
public static void manipulateFiles(File[] filesInDirPassed, int fileCount) throws IOException
{
for(int i = 0; i < filesInDirPassed.length; i++)
{
File currentFile = filesInDirPassed[i];
if(currentFile.isDirectory())
{
String local = currentFile.getAbsolutePath();
//String onedrive = current
manipulateFiles(currentFile.listFiles(), fileCount);
}
String name = currentFile.getName();
System.out.println("old filename: " + name);
String newName = String.valueOf(fileCount);
fileCount++;
File oldPath = new File(currentFile.getAbsolutePath());
System.out.println("oldPath: " + oldPath);
//currentFile.renameTo(new File(oldPath.toString()));
System.out.println("currentFile: " + currentFile);
String pathExtension = new String(currentFile.getAbsolutePath().substring(42));
pathExtension = pathExtension.replaceAll(name, newName);
File newPath = new File(absolutePathOnedrive + "/" + pathExtension);
System.out.println("newPath: " + newPath);
copyFileUsingJava7Files(oldPath, newPath);
File finalPath = new File(absolutePathOnedrive + "" + name);
//newPath.renameTo(new File(finalPath.toString()));
//copyFileUsingJava7Files(newPath, finalPath);
System.out.println("renamed: " + name + "to: " + newName + ", copied to one drive, and changed back to original name");
}
}
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}

Java is being told that C:\Users\talain\Desktop\marketingOriginal\FX Rates\FY17\Q11\Week_12___February_12_2016.xls -> C:\Users\talain\Desktop\fakeOnedrive\FX Rates\FY17\Q11\0 is a file, which isn't true. Check the line where the error originates from and see if you are using a lambda expression anywhere.

Related

Java how to read files recursive

I want to read all files recursive inside a given path and show the path and Byte size in the output of every single File.
public class ReadFilesInPathRecursion {
public void listFiles (String startDir) {
File dir = new File(startDir);
File[] files = dir.listFiles();
if (files!=null && files.length >= 0) {
for(File file : files) {
if(file.isDirectory()) {
listFiles(file.getAbsolutePath()); // Recursion (absolute)
} else {
System.out.println(file.getName() + " (size in bytes: " + file.length() + ") " + "(path: " + file.getAbsoluteFile() + ")");
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ReadFilesInPathRecursion test = new ReadFilesInPathRecursion();
String startDir = sc.next();
test.listFiles(startDir);
}

How do I exlude files with a certain extension from a directory file list?"

I am creating a list of files under one Dir recursively. I have one variable( UNPACK_EXT ) defined asa constant and imported to exclude from the search / filelist.
the goal is to return a file list of all files that contain the (STATS_FILE ) variable with out searching any dir that contain ( UNPACK_EXT )
this is part of the code:
I pass in a variable called baseDir, this is the starting point of my search. I only want to list file that match (STATS_FILE ), however due to the size of directories that contain (UNPACK_EXT ) in the dir name I need to exclude these, as they are already available in other part's of application.
Spublic class FindStatFilesTag extends BaseTag
{
private String baseDir;
#Override
public void doTag() throws JspException, IOException
{
if ((!isEmpty(var)) && (!isEmpty(baseDir)))
{
if (baseDir.contains("TS"))
{
String pmr = baseDir;
JspContext context = getJspContext();
baseDir = BASE_SF_PATH + "TS" + pmr.charAt(2) + pmr.charAt(3) + pmr.charAt(4) + "/" + pmr.charAt(5) + pmr.charAt(6) + pmr.charAt(7) + "/" + baseDir;
List<File> fileList = new ArrayList<File>();
String startDir = baseDir;
String dirName = startDir + "/" ;
File dir = new File(dirName);
fileList.addAll(listAll(dir));
Map<String, List<FileInfo>> fileInfoMap = new TreeMap<String, List<FileInfo>>();
for (Iterator<File> iter = fileList.iterator(); iter.hasNext();)
{
File file = iter.next();
String name = file.getAbsolutePath();
String shortName = "";
if ((name.contains(STATS_FILE)) && (!name.contains(UNPACK_EXT)))
{
shortName = name.substring(name.indexOf(STATS_FILE));
}
FileInfo fileInfo = new FileInfo(name, "", file.length());
if (fileInfoMap.containsKey(shortName))
{
List<FileInfo> fileInfoList = fileInfoMap.get(shortName);
if (!fileInfoList.contains(fileInfo))
{
fileInfoList.add(fileInfo);
Collections.sort(fileInfoList);
}
}
else
{
List<FileInfo> fileInfoList = new ArrayList<FileInfo>();
fileInfoList.add(fileInfo);
fileInfoMap.put(shortName, fileInfoList);
}
}
context.setAttribute(var, fileInfoMap);
}

How to get the path of a file but without the actual file name

For example C:\Desktop and not C:\Desktop\file.txt.
Here's the code, what can i do to get only the path excluding the actual name of the file or do i have to mechanically remove the name part(String) with the split("\") method.
import java.io.*;
public class FilesInfo {
File file = new File("C:\\Users\\CCKS\\Desktop\\1");
public void viewFiles() throws IOException {
File[] files = file.listFiles();
String path = "";
for(int i = 0; i < files.length; i++){
if(!files[i].isDirectory()){
System.out.println("[DIRECTORY]" + files[i].getPath() + " [NAME] " + files[i].toString() + " [SIZE] " + files[i].length() + "KB");
} else {
path = files[i].getAbsolutePath();
file = new File(path);
}
}
if(path.equals("")){
return;
} else {
viewFiles();
}
}
public static void main(String [] args){
try {
new FilesInfo().viewFiles();
} catch (Exception e){
e.printStackTrace();
}
}
}
Like this,
File file = new File("C:\Desktop\file.txt");
String parentPath= file.getParent();
File file = new File( "C:/testDir/test1.txt" );
String justPath = file.getParent();

Java Path Files.copy rename if exists

just a simple question, with a hard (for me) to find answer :D. Here is my code (im going to try to translate the spanish part):
File carpetanueva = new File("C:"+File.separator+"sistema" + File.separator +
fechasal+File.separator+doc);
carpetanueva.mkdirs();
carpetanueva.setWritable(true);
rutadestino = ("c:"+File.separator+"sistema" +
File.separator + fechasal+File.separator +
doc+File.separator+"imagen.jpg");
//realizo la copia de la imagen desde el jfilechooser a su destino:
Path desde = Paths.get(rutaorigen);
Path hacia = Paths.get(rutadestino);
try {
Files.copy(desde, hacia);
JOptionPane.showMessageDialog(null,
"Se adjunto la planilla de ambulancia correctamente");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "error: "+e.getLocalizedMessage());
}
I get "rutaorigen" (frompath) from a JFileChooser. And I create "rutadestino" (topath) by using some variables so this way i can give an order. The problem is.. .if directories and the file "imagen.jpg" already exists, it gives an error.. (exception).. How can i make to check if image already exists, and if it does, rename the new image to , for example, imagen2? I cant figure out code, because im a newbie, I did a research and couldnt find something like this! Thanks in advance :)
OK, here is a quick solution if src is a Path to the file you want to copy, dst a Path to the file you want to write, and newName a Path to the file you want to rename to:
if (Files.exists(dst))
Files.move(dst, newName);
Files.copy(src, dst);
Note that you can use the methods in Path to facilitate your path building: .resolve(), .resolveSibling(), .relativize().
Edit: here is a function which will return a suitable name given a directory (dir), a base filename baseName and an "extension" (without the dot) extension:
private static Path findFileName(final Path dir, final String baseName,
final String extension)
{
Path ret = Paths.get(dir, String.format("%s.%s", baseName, extension));
if (!Files.exists(ret))
return ret;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
ret = Paths.get(dir, String.format("%s%d.%s", baseName, i, extension));
if (!Files.exists(ret))
return ret;
}
throw new IllegalStateException("What the...");
}
I think this link will help How do I check if a file exists?
So for your case, probably do something like:
File toFile = new File(rutadestino);
if (toFile.exists()) {
// rename file
toFile.renameTo(new File("newFilePath/newName.jpg"));
} else {
// do something if file does NOT exist
}
Hope that helps! For more info, also check the Java Docs for File
sory late. but my code can help to litle bit.
public void copyFile(File source, File dest) throws IOException,
FileAlreadyExistsException {
File[] children = source.listFiles();
if (children != null) {
for (File child : children) {
if (child.isFile() && !child.isHidden()) {
String lastEks = child.getName().toString();
StringBuilder b = new StringBuilder(lastEks);
File temp = new File(dest.toString() + "\\"
+ child.getName().toString());
if (child.getName().contains(".")) {
if (temp.exists()) {
temp = new File(dest.toString()
+ "\\"
+ b.replace(lastEks.lastIndexOf("."),
lastEks.lastIndexOf("."), " (1)")
.toString());
} else {
temp = new File(dest.toString() + "\\"
+ child.getName().toString());
}
b = new StringBuilder(temp.toString());
} else {
temp = new File(dest.toString() + "\\"
+ child.getName());
}
if (temp.exists()) {
for (int x = 1; temp.exists(); x++) {
if (child.getName().contains(".")) {
temp = new File(b.replace(
temp.toString().lastIndexOf(" "),
temp.toString().lastIndexOf("."),
" (" + x + ")").toString());
} else {
temp = new File(dest.toString() + "\\"
+ child.getName() + " (" + x + ")");
}
}
Files.copy(child.toPath(), temp.toPath());
} else {
Files.copy(child.toPath(), temp.toPath());
}
} else if (child.isDirectory()) {
copyFile(child, dest);
}
}
}
}
features :
1. rename if file exist in the destination. example: document.doc if exist document (1).doc if exist document (2).doc if exist ...
2. copy all file from source (only file) to one folder in destination
The code below checks if the file already exists in destination, if it does, it appends #1 to file name just before the extension. If that file name also exists, it keeps appending #2,#3,#4... till the file name doesn't exist in destination. Since () and spaces create problems in Unix environment, I used # instead.
You can extend this and do a SUMCHECK if the file in destination with the identical name also has the same content and act accordingly.
Credit goes to johan indra Permana
String lastEks = file.getName().toString();
StringBuilder b = new StringBuilder(lastEks);
File temp = new File(backupDir.toString() + File.separator + file.getName().toString());
if (file.getName().contains(".")) {
if(temp.exists()) {
temp = new File(backupDir.toString() + File.separator +
b.replace(lastEks.lastIndexOf("."), lastEks.lastIndexOf("."),"#1").toString());
} else {
temp = new File(backupDir.toString() + File.separator + file.getName().toString());
}
b = new StringBuilder(temp.toString());
} else {
temp = new File(backupDir.toString() + File.separator + file.getName());
}
if (temp.exists()) {
for (int x=1; temp.exists(); x++) {
if(file.getName().contains(".")) {
temp = new File (b.replace(
temp.toString().lastIndexOf("#"),
temp.toString().lastIndexOf("."),
"#" + x ).toString());
} else {
temp = new File(backupDir.toString() + File.separator
+ file.getName() + "#" + x );
}
}
Files.copy(file.toPath(), temp.toPath());
} else {
Files.copy(file.toPath(), temp.toPath());
}

Detecting the last folder from a list

I have several files, thing is that i need to know which one was the last created according to the numbers I give them automatically.
For example if i have: file1, file2, file3 I want to receive the file3. I can't do this with "last modified" because I have other folders and files in the same directory.
Also to this last file I would like to increment his number in 1.
Put the files in a list and sort it lexically, then take the last one.
Ofcourse you have to filter out the ones you are looking for with regex or contains/startswith/endswith
Here is an alternate simple solution.
import java.io.File;
public class FileUtility {
private static final String FOLDER_PAHT = "D:\\Test";
private static final String FILE_PREFIX = "file";
/**
* #param args
*/
public static void main(String[] args) {
int lastFileNumber = getLastFileNumber();
System.out.println("In folder " + FOLDER_PAHT + " last file is " + FILE_PREFIX + lastFileNumber);
if(incrementFileNumber(lastFileNumber)) {
System.out.println("After incrementing the last file becomes : FILE_PREFIX" + lastFileNumber + 1);
} else {
System.out.println("Some error occured while updating file number.");
}
}
private static int getLastFileNumber(){
int maxFileNumber = 0;
File folder = new File(FOLDER_PAHT);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String fileName = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && fileName.contains(FILE_PREFIX)) {
try {
int fileNumber = Integer.parseInt(fileName.substring(FILE_PREFIX.length(), fileName.indexOf(".")));
if(maxFileNumber < fileNumber) {
maxFileNumber = fileNumber;
}
} catch (NumberFormatException e) {
// Because there can be files with starting name as FILE_PREFIX but not valid integer appended to them.
//NOthing to do
}
}
}
return maxFileNumber;
}
private static boolean incrementFileNumber(final int oldNumber) {
File oldfile =new File(FOLDER_PAHT + File.separator + FILE_PREFIX + oldNumber);
File newfile =new File(FOLDER_PAHT + File.separator + FILE_PREFIX + (oldNumber + 1) + ".txt");
return oldfile.renameTo(newfile);
}
}
public static void main (String[] args) throws Exception
{
File foldersContainer = new File("c:/test");
String latestFileName = "";
Integer highestFileNumber = 0;
for (File tmpFile : foldersContainer.listFiles()){
if (tmpFile.isFolder()) {
int currentNumber = extractFileNumber(tmpFile.getName());
if (currentNumber > highestFileNumber){
highestFileNumber = currentNumber;
latestFileName = tmpFile.getName();
}
}
}
latestFileName.replace(highestFileNumber.toString(),
(++highestFileNumber).toString());
System.out.println("Latest file (incremented): " + latestFileName);
}
private static int extractFileNumber(String name){
for (int x=name.length()-1; x >= 0; x--)
if (!Character.isDigit(name.charAt(x)))
return Integer.parseInt(name.substring(x+1));
return -1;
}
If the filename before the last number can contain numbers, then you should use lastIndexOf to be sure of finding only the occurrence you really want to increment.
instead of
latestFileName.replace(highestFileNumber.toString(),
(++highestFileNumber).toString());
you should use
latestFileName = latestFileName
.substring(0,latestFileName.lastIndexOf(highestFileNumber.toString()))
.concat((++highestFileNumber).toString());
Ok, here's an alternative. I'm assuming that the file name is known and they have the same name.
public static void main(String[] args) {
File dir = new File("directory of the files");
File [] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.startsWith("folder");
}
});
for (File file : files) {
System.out.println(file.getName());
}
System.out.println("---------");
List<File> myFile = new ArrayList<>(Arrays.asList(files));
Collections.sort(myFile, new Comparator<File>() {
#Override
public int compare(File f1, File f2) {
// TODO Auto-generated method stub
int numberF1 = Integer.parseInt(f1.getName().replace("folder",""));
int numberF2 = Integer.parseInt(f2.getName().replace("folder",""));
return Integer.compare(numberF1, numberF2);
}
});
for (File file : myFile) {
System.out.println(file.getName());
}
}
Output :
folder10
folder2
folder20
folder250
---------
folder2
folder10
folder20
folder250

Categories