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
Related
I am developing a java application to perform operations with files.
In particular, I perform move and copy of files .. and I have programmed two functions.
Functions take strings such as sourcePath and targetPath as parameters.
I am developing on a mac, and I have given 777 permissions to the folders I need.
But I have the problem, that when I pass paths to the copyFile and moveFile functions I lose the last "/" of the path and consequently get a java.nio.File: NoSuchFileException exception.
I have read both the Java and online documentation but have not found any answers.
I accept any suggestion or advice ... I just add that by manually forcing the path inside the function, then not passing sourcePath and targetPath, the two functions behave as they should.
copyFile:
public static boolean copyFile(String sourcePath, String targetPath) throws IOException {
boolean fileCopied = true;
// if i pass sourcePath i lost the last /
File dirFiles = new File("/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_da_inviare_a_icbpi/");
File[] listOfFiles = dirFiles.listFiles();
String dest = "/Users/myname/Documents/deleghe/local/F24_CT/deleghe_da_inviare_a_icbpi/";
for (File file : listOfFiles) {
Files.copy(file.toPath(),
(new File(dest + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
return fileCopied;
}
moveFile:
public static boolean moveFile(String sourcePath, String targetPath) throws IOException {
boolean fileMoved = true;
// if i pass sourcePath i lost the last /
File dirFiles = new File("/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_da_inviare_a_icbpi/");
File[] listOfFiles = dirFiles.listFiles();
String dest = "/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_inviate/";
for (File file : listOfFiles) {
if (file.length() >= 968 && file.length() <= 2057) {
Files.move(file.toPath(),
(new File(dest + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
System.out.println("File spostato correttamente: " + file.getName() + "!! \n");
} else {
System.out.println("Non è stato possibile spostare il file: " + file.getName() + "!! \n");
}
}
return fileMoved;
}
try to use Paths.get(dest, file.getName()).toUri() instead of dest + file.getName() (it is not best practice)
you are not losing anything, you just reading files from directory and your code is working without any exception. Check your directories and files inside them one more time
I have a program that is supposed to rename all files within an entire folder (with sub-folders) to a temporary file name, copy those to a different directory, then change the temp filename back to the original filename. During this process I would like to keep all folder names the same. When I run the code below, all it does is change the name of the top-level folders in the path that i specify:
package shortenFilenames;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class shortenFilenameClass
{
public static void main(String[] args) throws IOException
{
String absolutePathLocal = "C:\\Users\\talain\\Desktop\\marketingOriginal"; //original files
String absolutePathOnedrive= "C:\\Users\\talain\\Desktop\\fakeOnedrive"; //path to onedrive
File local = new File(absolutePathLocal);
File onedrive = new File(absolutePathOnedrive);
File[] filesInDir = local.listFiles();
for(int i = 0; i < filesInDir.length; i++)
{
String name = filesInDir[i].getName();
System.out.println(name);
String newName = String.valueOf(i);
File oldPath = new File(absolutePathLocal + "\\" + newName);
System.out.println("oldPath: " + oldPath);
filesInDir[i].renameTo(new File(oldPath.toString()));
File newPath = new File(absolutePathOnedrive + "\\" + newName);
copyFileUsingJava7Files(oldPath, newPath);
newPath.renameTo(new File(newPath.toString()));
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());
}
}
I just did the following and it copied whatever files were in the first path into the second path. If it fails for you, show me the error output.
for(int i = 0; i < filesInDir.length; i++)
{
String name = filesInDir[i].getName();
System.out.println(name);
Files.copy(new File(absolutePathLocal + "\\" + name).toPath(),new File(absolutePathOnedrive + "\\" + name).toPath());
}
Your code also assumes that those directories already exist on your system otherwise you will run into a FileNotFound exception.
I need to process a high volume of resumes. And want to use this parser:
https://github.com/antonydeepak/ResumeParser
But you run it in powershell with the file to read and the output file.
But I do not know how to automate this, so it read a whole folder containing the resumes.
I know some Java, but cant open the code. Is scripinting in powershell the way to go?
Thanks!
> java -cp '.\bin\*;..\GATEFiles\lib\*;..\GATEFILES\bin\gate.jar;.\lib\*'
code4goal.antony.resumeparser.ResumeParserProgram <input_file> [output_file]
Either make a batch file from an edited directory listing, or write a program.
As this is stackoverflow:
So starting with the same classpath (-cp ...) you can run your own program
public void static main(String[] args) throws IOException {
File[] files = new File("C:/resumes").listFiles();
File outputDir = new File("C:/results");
outputDir.mkDirs();
if (files != null) {
for (File file : files) {
String path = file.getPath();
if (path.endsWith(".pdf")) {
String output = new File(outputDir,
file.getName().replaceFirst("\\.\\w+$", "") + ".json").getPath();
String[] params = {path, output);
ResumeParserProgram.main(params);
// For creating a batch file >x.bat
System.out.println("java -cp"
+ " '.\\bin\\*;..\\GATEFiles\lib\\*;"
+ "..\\GATEFILES\\bin\\gate.jar;.\\lib\\*'"
+ " code4goal.antony.resumeparser.ResumeParserProgram"
+ " \"" + path + "\" \"" + output + "\"");
}
}
}
}
Check that this works, that ResumeParserProgram.main is reenterable.
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
I was just wondering if the code I made will work to create multiple directories within each other. I used this as a reference.
String username = enterUserTF.getText(); //the username the user enters in a textfield.
boolean myGamesFolderSuccess = new File(System.getProperty("user.home"), "My Games").mkdir();
boolean mainFolderSuccess = new File("My Games", "Type King").mkdir();
boolean userSuccess = new File("TypeKing", username).mkdir(); //creates a folder with the users username.
if(myGamesFolderSuccess){
if(mainFolderSuccess){
if(userSuccess){
System.out.println("Directory " + username + " created.");
File f = new File(username + "/test.txt");
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Could not create user's file.");
}
}
}
}
}
}
So to sum up the above, I made the the first directory "My Games" in user.home, then placed my game's name, "Type King" in that directory, and whenever the user enters a username, I want a directory to be created that is their username. File f just checks for a file in the username directory.
It is recommended to use the mkdirs method of the File class instead of checking multiple status flags when creating nested directories. Also, never use concatenation for creating File objects/paths.
Also, if you want your game to be portable, make sure you don't have special characters in your directory names like a space etc.Why are you asking user for the name instead of retrieving it from user.name system property? Something like this should work:
String username = System.getProperty("user.name");
File myGamesDir = new File(System.getProperty("user.home"), "my-games");
File typeKingDir = new File(myGamesDir, "type-king");
File userDir = new File(typeKingDir, username);
boolean userSuccess = userDir.mkdirs();
if(userSuccess){
System.out.println("Directory " + username + " created.");
File f = new File(userDir, "test.txt");
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Could not create user's file.");
}
}
}
If you pass a full path to File.mkdirs (with an s) it will make an arbitrarily deep directory structure. You don't have to build paths one directory at a time. If the directories already exist, or if some of them exist, it will still work as you expect.
import java.io.File;
import javax.swing.JOptionPane;
class Dirs {
public static void main(String[] args) throws Exception {
String subDir = "My Games|Type King";
String userName = JOptionPane.showInputDialog(
null,
"Who are you?");
subDir += "|" + userName;
String[] parts = subDir.split("\\|");
File f = new File(System.getProperty("user.home"));
for (String part : parts) {
f = new File(f, part);
}
boolean madeDir = f.mkdirs();
System.out.println("Created new dir: \t" + madeDir + " \t" + f);
f = new File(f, "eg.txt");
if (!f.exists()) {
boolean madeFile = f.createNewFile();
System.out.println(
"Created new file: \t" + madeFile + " \t" + f );
}
}
}
Output
Created new dir: true C:\Users\Andrew\My Games\Type King\BilboBaggins
Created new file: true C:\Users\Andrew\My Games\Type King\BilboBaggins\eg.txt
I think its better to use existing functionality available in the API. If you don't have any restrictions consider switching to the latest JDK. In 1.7 Oracle did introduce so many enhancements including IO and New IO.
For creating multiple directories within each other you can take advantage of Files.createDirectories available since 1.7. "It will create a directory by creating all nonexistent parent directories first."