I'm stuck with the fact that no folder is made.
private static File createNewTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
String baseNamePrefix = System.currentTimeMillis() + "_" + Math.random() + "-";
LOG.info(System.getProperty("java.io.tmpdir"));
File tempDir = new File(baseDir, baseNamePrefix + "0");
LOG.info(tempDir.getAbsolutePath());
tempDir.mkdirs();
if (tempDir.exists()) {
LOG.info("I would be happy!");
}
else {
LOG.info("No folder there");
}
return tempDir;
}
Is there any wrong with it? I can get the LOG that no folders are there...
Your code is fine, but your conditional is wrong:
if (tempDir.exists()) {
LOG.info("I would be happy!");
}
else {
LOG.info("No folder there");
}
The folder is created indeed, you can check that by getting the path and opening on Explorer.
EDIT: It works on Windows at least. I cleaned it up a bit:
public static void main() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
File tempDir = new File(baseDir, "test0");
System.err.println(tempDir.getAbsolutePath());
tempDir.mkdir();
System.err.println("is it a dir? " + tempDir.isDirectory());
System.err.println("does it exist? " + tempDir.exists());
}
Output:
C:\Users\marsch1\AppData\Local\Temp\test0
is it a dir? true
does it exist? true
Related
Hey I'm trying to delete a image (file) but I can't :(
That how I upload the image:
try {
List<String> imagesPaths = new ArrayList<>();
for (String image : imagesBytes)
{
String base64Image = image.split(",")[1];
byte[] imageByte = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
String folder = "C:/images/" + LoggedInUser.UserId();
File newDirectory = new File(folder);
if (!newDirectory.exists())
{
newDirectory.mkdirs();
}
long timeMilli = new Date().getTime();
String imageType = image.substring("data:image/".length(), image.indexOf(";base64"));
String path = timeMilli + "." + imageType;
Files.write(Paths.get(folder, path), imageByte);
String newPath = LoggedInUser.UserId() + "/" + path;
imagesPaths.add(newPath);
}
logger.debug("uploadImages() in ImageService Ended by " + LoggedInUser.UserName());
return new ResponseEntity<>(imagesPaths, HttpStatus.OK);
} catch (Exception e) {
throw new ApiRequestException(e.getMessage());
}
And this how I delete it :
List<ImageJpa> images = imageRepository.findByStatus(Image.UNUSED.status);
System.out.println(images.size() + ": Images are not used");
images.forEach(image -> {
String imagePath = "C:/images/" + image.getPath();
System.out.println(imagePath);
File imagePathFile = new File(imagePath);
if (imagePathFile.exists())
{
boolean isDeleted = imagePathFile.delete();
if (isDeleted)
{
imageRepository.deleteById(image.getId());
System.out.println("Deleted the file: " + imagePathFile.getName());
} else {System.out.println("Failed to delete the file. :" + imagePathFile.getName());}
}else {
System.out.println("Already Deleted");
}
});
Always I got (Failed to delete the file ...)
Note : The image will deleted if I ReRender the the project again or close and open the IDE.
The problem was on other function :\
I was open the files after save it without CLOSE the connection after it !
This one what was messing on the read files
inputStream.close();
I have the following code below, which is used to list all the files within specific folders/directories.
For mac this works perfectly, but when it comes to windows I get a java.lang.NullPointerException. I am not completely sure how I would fix it, I am aware that it means one of the directory File variables are passed as Null when being put into the function. But I am not sure how to check whether the directory is null and why exactly it creates an error on only that particular directory as it works on all the other directories and the directory it doesn't work on is just the regular documents directory on Windows. I have made a small comment on the three lines where the java.lang.NullPointerException error is showing.
I have also tried to fix it by surrounding the file list function to check whether the folder is null or not. But that doesn't work as it is already to late, the null error is already happening at the File variable declaration.
public static void main() throws IOException {
if (isMac()) {
listFilesForFolderMac(folderMac1);
listFilesForFolderMac(folderMac2);
listFilesForFolderMac(folderMac3);
listFilesForFolderMac(folderMac4);
listFilesForFolderMac(folderMac5);
listFilesForFolderMac(folderMac6);
listFilesForFolderMac(folderMac7);
} else if (isWindows()) {
listFilesForFolderWin(folderWin1);
listFilesForFolderWin(folderWin2);
listFilesForFolderWin(folderWin3);
listFilesForFolderWin(folderWin4);
listFilesForFolderWin(folderWin5);
listFilesForFolderWin(folderWin6);
}
}
public static boolean isWindows() {
return (OS.indexOf("win") >= 0);
}
public static boolean isMac() {
return (OS.indexOf("mac") >= 0);
}
public static void listFilesForFolderMac(final File folder) throws IOException {
PrintWriter writToDoc = new PrintWriter(new FileWriter("/Users/" + username + "/Documents/files.txt",true));
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolderMac(fileEntry);
} else {
writToDoc.println(fileEntry.getName());
}
}
writToDoc.close();
}
public static void listFilesForFolderWin(final File folder) throws IOException {
PrintWriter writToDoc = new PrintWriter(new FileWriter("c:\\users\\" + username + "\\Documents\\files.txt",true));
for (final File fileEntry : folder.listFiles()) { //Error here
if (fileEntry.isDirectory()) {
listFilesForFolderWin(fileEntry); //Error here
} else {
writToDoc.println(fileEntry.getName());
}
}
writToDoc.close();
}
final static File folderMac1 = new File("/Users/" + username + "/Pictures");
final static File folderMac2 = new File("/Users/" + username + "/Documents");
final static File folderMac3 = new File("/Users/" + username + "/Movies");
final static File folderMac4 = new File("/Users/" + username + "/Music");
final static File folderMac5 = new File("/Users/" + username + "/Downloads");
final static File folderMac6 = new File("/Users/" + username + "/Applications");
final static File folderMac7 = new File("/Users/" + username + "/Desktop");
final static File folderWin1 = new File("C:\\Users\\" + username + "\\Desktop");
final static File folderWin2 = new File("C:\\Users\\" + username + "\\Downloads");
final static File folderWin3 = new File("C:\\Users\\" + username + "\\Documents"); //Error here
final static File folderWin4 = new File("C:\\Users\\" + username + "\\Pictures");
final static File folderWin5 = new File("C:\\Users\\" + username + "\\Music");
final static File folderWin6 = new File("C:\\Users\\" + username + "\\Videos");
I get the following error stated below.
Exception in thread "main" java.lang.NullPointerException
at script.MyClass.listFilesForFolderWin(MyClass.java:200)
at script.MyClass.listFilesForFolderWin(MyClass.java:202)
at script.MyClass.main(MyClass.java:155)
There are some folders in Windows that Java can see but not see into, and some files that it sees as directories. To solve your problem, simply check before you try to list the files:
if (fileEntry.isDirectory()&&fileEntry.listFiles()!=null) {
listFilesForFolderWin(fileEntry);
}
I have messed around with the file commands that Java has, and usually when you get a NullPointerExcpetion, it means that the directory you have given it is wrong. I have not run your code on windows, but for that platform, all you need to do is follow the same file structure that you did with your Mac paths. Here is what your first variable should be:
final static File folderWin1 = new File("C:/Users/" + username + "/Pictures");
All of the rest of your variables should follow the same structure. I hope this fixes your problem.
java.util.File can not process Window's "junction"s (a type of symbolic link), such as "My Documents" and "Pictures"
You will need to switch over to the NIO2 API and make use of the Paths API.
See Walking the File Tree which actually has an example for processing symbolic links
Extract from above link
#Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attr) {
if (attr.isSymbolicLink()) {
System.out.format("Symbolic link: %s ", file);
} else if (attr.isRegularFile()) {
System.out.format("Regular file: %s ", file);
} else {
System.out.format("Other: %s ", file);
}
System.out.println("(" + attr.size() + "bytes)");
return CONTINUE;
}
You may also want to have a look at Links, Symbolic or Otherwise for more details
I am trying to recursively iterate through the entire root directory that I arrive at after login to the FTP server.
I am able to connect, all I really want to do from there is recurse through the entire structure and and download each file and folder and have it in the same structure as it is on the FTP. What I have so far is a working download method, it goes to the server and gets my entire structure of files, which is brilliant, except it fails on the first attempt, then works the second time around. The error I get is as follows:
java.io.FileNotFoundException: output-directory\test\testFile.png
(The system cannot find the path specified)
I managed to do upload functionality of a directory that I have locally, but can't quite get downloading to work, after numerous attempts I really need some help.
public static void download(String filename, String base)
{
File basedir = new File(base);
basedir.mkdirs();
try
{
FTPFile[] ftpFiles = ftpClient.listFiles();
for (FTPFile file : ftpFiles)
{
if (!file.getName().equals(".") && !file.getName().equals("..")) {
// If Dealing with a directory, change to it and call the function again
if (file.isDirectory())
{
// Change working Directory to this directory.
ftpClient.changeWorkingDirectory(file.getName());
// Recursive call to this method.
download(ftpClient.printWorkingDirectory(), base);
// Create the directory locally - in the right place
File newDir = new File (base + "/" + ftpClient.printWorkingDirectory());
newDir.mkdirs();
// Come back out to the parent level.
ftpClient.changeToParentDirectory();
}
else
{
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
String remoteFile1 = ftpClient.printWorkingDirectory() + "/" + file.getName();
File downloadFile1 = new File(base + "/" + ftpClient.printWorkingDirectory() + "/" + file.getName());
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
}
}
}
}
catch(IOException ex)
{
System.out.println(ex);
}
}
Your problem (well, your current problem after we got rid of the . and .. and you got past the binary issue) is that you are doing the recursion step before calling newDir.mkdirs().
So suppose you have a tree like
.
..
someDir
.
..
someFile.txt
someOtherDir
.
..
someOtherFile.png
What you do is skip the dot files, see that someDir is a directory, then immediately go inside it, skip its dot files, and see someFile.txt, and process it. You have not created someDir locally as yet, so you get an exception.
Your exception handler does not stop execution, so control goes back to the upper level of the recursion. At this point it creates the directory.
So next time you run your program, the local someDir directory is already created from the previous run, and you see no problem.
Basically, you should change your code to:
if (file.isDirectory())
{
// Change working Directory to this directory.
ftpClient.changeWorkingDirectory(file.getName());
// Create the directory locally - in the right place
File newDir = new File (base + "/" + ftpClient.printWorkingDirectory());
newDir.mkdirs();
// Recursive call to this method.
download(ftpClient.printWorkingDirectory(), base);
// Come back out to the parent level.
ftpClient.changeToParentDirectory();
}
A complete standalone code to download all files recursively from an FTP folder:
private static void downloadFolder(
FTPClient ftpClient, String remotePath, String localPath) throws IOException
{
System.out.println("Downloading folder " + remotePath + " to " + localPath);
FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);
for (FTPFile remoteFile : remoteFiles)
{
if (!remoteFile.getName().equals(".") && !remoteFile.getName().equals(".."))
{
String remoteFilePath = remotePath + "/" + remoteFile.getName();
String localFilePath = localPath + "/" + remoteFile.getName();
if (remoteFile.isDirectory())
{
new File(localFilePath).mkdirs();
downloadFolder(ftpClient, remoteFilePath, localFilePath);
}
else
{
System.out.println("Downloading file " + remoteFilePath + " to " +
localFilePath);
OutputStream outputStream =
new BufferedOutputStream(new FileOutputStream(localFilePath));
if (!ftpClient.retrieveFile(remoteFilePath, outputStream))
{
System.out.println("Failed to download file " + remoteFilePath);
}
outputStream.close();
}
}
}
}
I have text file but do not know the path where it saved in my computer.I only know name of the file. now how i get path of that file(Address/location) present in computer through java code.
Here is the to search the file on the computer
public class Operation {
public static void main(String [] args) {
File[] files = File.listRoots();
for(File f : files){
System.out.println(f.getPath());
parseAllFiles(f.getPath());
}
}
public static void parseAllFiles(String parentDirectory) {
String rootDir = System.getenv("SystemDrive");
System.out.println("PARSED FILES ::" + rootDir);
File[] filesInDirectory = new File(parentDirectory).listFiles();
if(filesInDirectory!=null){
for (File f : filesInDirectory){
if(f.isDirectory()){
parseAllFiles(f.getAbsolutePath());
}
System.out.println("Current File -> " + f);
System.out.println(f.getPath());
File f1 = new File(f.getPath()+"infos.txt"); //name of file
System.out.println("filename : " + f1.exists());
boolean exists = f1.exists();
System.out.println("exists : "+exists);
if (exists) {
System.out.println("Path::" + f1.getPath());
break;
} else {
System.out.println("Does not exist");
}
}
}
}
}
The java.nio.file package provides programmatic support for the features to find files and to do recursive search . Here is the java tutorial to help you achieve that:
http://docs.oracle.com/javase/tutorial/essential/io/find.html
I'm trying to create a new dir in Java but it doesn't work. I'm wondering why because I tried mkdir() first and then I tried mkdirs() which is supposed to create unexistant directories.
I wrote :
boolean status = new File("C:\\Users\\Hito\\Desktop\\test").mkdir();
// status = false
then I wrote
boolean status = new File("C:\\Users\\Hito\\Desktop\\test").mkdirs();
// status still = false.
A clue ?
This is faster to type, and does not need double slashes:
boolean status = new File("C:/Users/Hito/Desktop/test").mkdir();
if you still get errors, check if the parent directory exists, and if file is writeable.
String path = "C:/Users/Hito/Desktop/";
File file = new File(path);
If (!path.exists()) {
System.out.println("path does not exist:" + path);
} else {
File dir = new File(path + "test");
if (!dir.canWrite()) {
System.out.println("dir not writeable" + path + "test");
}
}
File file = new File("C:/Users/Hito/Desktop/test");
file.mkdirs();
file.createNewFile();
Check your permissions
Try it:
boolean status = new File("C:\\Users\\Hito\\Desktop\\test").canWrite();
It's kinda strange because I used the windows search and I could find my directory BUT it's not located at :
C:\Users\Hito\Desktop
but at :
C:\Users\Hito\Desktop\Dropbox\Stage\Applic_WIDT
which is the directory containing my application.