I wrote a script to print the names of all files and folders, recursively, to console. I want to edit this to print it in an excel spreadsheet/csv like so :
Folder
FullPath/Folder/File.extension, Folder, Extension
...
...
Recursively do this for all documents in the folder.
Here is my script to do it in Console :
package test;
import java.io.File;
import java.io.IOException;
public class RecursiveFileDisplay {
public static void main(String[] args) {
File currentDir = new File("."); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
displayDirectoryContents(file);
} else {
System.out.println(" file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
How can I adapt this to print to an Excel spreadsheet or CSV?
Thanks.
Related
Please I am trying to apply setReadOnly() function to all documents having the .docx and .pptx file extension in my C: drive. As in the readonly show apply to any document that has the file extension in C: directory.
Please someone show assist me on how to implement that. This is what I have able to come with but I don’t think is the correct way nor the correct code
import java.io.File;
import java.io.IOException;
public class FileReadAttribute {
public static void main(String[] args) throws IOException {
File file = new File("C:*.docx");
file.setReadOnly();
if(file.canWrite()) {
System.out.println("This file is writable");
} else {
System.out.println("This file is read only");
}
}
}
try this:
import java.io.File;
import java.io.IOException;
public class FileReadAttribute {
public static void main(String[] args) throws IOException {
File c_drive = new File("C:\\");
setPermission(c_drive);
}
private static void setPermission(File parent) {
File[] files = parent.listFiles();//get all files of this directory
for (File file : files) {
if (file.isDirectory()) {
setPermission(file); //set permission of the files in this directory
} else {
String fileExtension = getFileExtension(file);
if (fileExtension.equals("docx") || fileExtension.equals("pptx")) {
file.setReadOnly();
}
}
}
}
private static String getFileExtension(File file) {
String name = file.getName();
return name.substring(name.lastIndexOf(".") + 1);
}
}
You can use FileNameFilter. This should work
File dir = new File("/users/blah/dirname");
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".docx");
}
});
if (files != null) {
Stream.of(files).forEach(File::setReadOnly);
}
If you are using Java less than 8. Replace Stream.of with traditional for loop.
Below is the code for copy a file from one directory to another directory.
For eg: if the filename is Red-Already over,Red-Already Over(slow),NEFFEX-Destiny,then it should create a directory name red and copy the file into it,
For another artist it should NEFFEX folder and copy the file into it.
The problem is that it can create the directory if Files.copy is commented.But it is unable to create a dir but copy the file when Files.copy is uncommented.
The file is not playable because it doesn't have extension(seems the file is not getting copied properly).
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class OrgLogic {
String path="C:\\Users\\Fawkes\\Music\\Music\\";
String target_path="C:\\Output\\";
OrgLogic() throws IOException{
File f=new File(path); //loads the input dir path
File dir=new File(target_path); //loads the output dir path
dir.mkdir();//create a new dir name output
File[] total_file=f.listFiles();//get the total number of file
//System.out.println(total_file.length);//prints the total number of the file
for(int i=0;i<total_file.length;i++) {
String name=total_file[i].getName();
String new_name=name.substring(0, name.indexOf("-")-1);
dir=new File(target_path+new_name);
if(dir.exists()) {
//new File(new_path+new_name).mkdir();
Files.copy(total_file[i].toPath(), dir.toPath(),StandardCopyOption.REPLACE_EXISTING);
}
else {
//new File(target_path+new_name).mkdir();
dir.mkdir();
Files.copy(total_file[i].toPath(), dir.toPath(),StandardCopyOption.REPLACE_EXISTING);
}
}
}
public static void main(String[] args) {
try {
new OrgLogic();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The filename path is:
Source:
C:\Users\Fawkes\Music\Music\Red-Already over
C:\Users\Fawkes\Music\Music\Red-Already over(slow)
C:\Users\Fawkes\Music\Music\NEFFEX-Destiny
Destination:
C:\Output\
For eg:
C:\Output\Red\Already over
C:\Output\Red\Already over(slow)
C:\Output\NEFFEX\Destiny
it is declared as variable:path and target_path
(Feature: it would be good that while pasting codes in here Line Number should be there.)
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 OrgLogic {
String path="C:\\Users\\Fawkes\\Music\\Music\\";
String target_path="C:\\Output\\";
OrgLogic() throws IOException{
File f=new File(path); //loads the input dir path
File dir=new File(target_path); //loads the output dir path
dir.mkdir();//create a new dir name output
File[] total_file=f.listFiles();//get the total number of file
//System.out.println(total_file.length);//prints the total number of the file
for(int i=0;i<total_file.length;i++) {
String name=total_file[i].getName();
String new_name=name.substring(0, name.indexOf("-")-1);
dir=new File(target_path+new_name);
if(dir.exists()) {
Path src=Paths.get(total_file[i].getPath());
Path dest=Paths.get(dir.getAbsolutePath().concat("\\").concat(total_file[i].getName()));
Files.copy(src, dest ,StandardCopyOption.REPLACE_EXISTING);
System.out.println("Files copied: "+(i+1)+"/"+total_file.length);
}
else {
dir.mkdir();
Path src=Paths.get(total_file[i].getPath());
Path dest=Paths.get(dir.getAbsolutePath().concat("\\").concat(total_file[i].getName()));// only needed to add this line.
Files.copy(src, dest ,StandardCopyOption.REPLACE_EXISTING);
System.out.println("Files copied: "+(i+1)+"/"+total_file.length);
}
}
}
public static void main(String[] args) {
try {
new OrgLogic();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've created a tool that checks pdf files for errors. The tool selects with a filechooser a directory, checks if there are pdf files and scans them. But I want that the tool checks recursively the directory. If I try this code:
public class RecursiveFileDisplay {
public static void main(String[] args) {
File currentDir = new File("C://Users//Tommy//Desktop"); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
displayDirectoryContents(file);
} else {
if (file.getName().endsWith((".pdf"))) {
System.out.println(" file:" + file.getCanonicalPath());
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
the tool will show me for each directory on a Desktop a new list and doesn't sum up all the results in one list...:
If you want your program to create a whole list with all the files processed, then you have to modify your displayDirectoryContent method as following:
public static List<File> displayDirectoryContents(File dir) {
ArrayList<File> rtnFiles = new ArrayList<File>();
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
rtnFiles.addAll(displayDirectoryContents(file));
} else {
if (file.getName().endsWith((".pdf"))) {
System.out.println(" file:" + file.getCanonicalPath());
rtnFiles.add(file);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return rtnFiles;
}
This way, it will return you with all the files found/processed. If you want this method only return you with failed files, then you will have to check not only the file is a .pdf file, but it is ok/failed, and then add to the list.
If you want to controll sum, then you can create a Java Class with two Integers one for pdf found files, and other for pdf failed found files. Recursively you can cum it up in the same way I build the list.
Hope it helps.
You can use the java.nio.file.Files.walkFileTree
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
public class FolderRecurs {
public Path pathToStart = Paths.get("The_URI_OF_THE_ROOT_DIRECTORY");
public List<File> listPDF = new ArrayList<>();
public FolderRecurs(Path pathToStart) {
this.pathToStart = pathToStart;
}
public void goRecurs() throws IOException{
Files.walkFileTree(pathToStart, new SimpleFileVisitor<Path>() {
//for folders
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs){
boolean error = false;
//your code
return error?FileVisitResult.TERMINATE : FileVisitResult.CONTINUE;
}
//for files
#Override
public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs){
boolean error = false;
//Convert path to file
File file = filePath.toFile();
if (file.getName().endsWith((".pdf"))){
listPDF.add(file);
}
//your code
return error?FileVisitResult.TERMINATE : FileVisitResult.CONTINUE;
}
});
}
}
import java.io.File;
import org.apache.commons.io.FilenameUtils;
public class Tester {
public static void main(String[] args) {
String rootPath = "F:\\Java\\Java_Project";
File fRoot = new File(rootPath);
File[] fsSub = fRoot.listFiles();
for (File file : fsSub) {
if(file.isDirectory()) continue;
String fileNewPath = FilenameUtils.removeExtension(file.getPath()) + "\\" + file.getName();
File fNew = new File(fileNewPath);
try {
file.renameTo(fNew);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I am trying to move the file to another directory,for instance,if the File path is
"C:\out.txt"
than I want to move to
"C:\out\out.txt"
If i try to print the original File and the new original information, the work well,But they just can not move successful.
I suggest to try Java 7 NIO2
Files.move(Path source, Path target, CopyOption... options)
I have a directory with files, directories, subdirectories, etc. How I can get the list of absolute paths to all files and directories using the Apache Hadoop API?
Using HDFS API :
package org.myorg.hdfsdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HdfsDemo {
public static void main(String[] args) throws IOException {
Configuration conf = new Configuration();
conf.addResource(new Path("/Users/miqbal1/hadoop-eco/hadoop-1.1.2/conf/core-site.xml"));
conf.addResource(new Path("/Users/miqbal1/hadoop-eco/hadoop-1.1.2/conf/hdfs-site.xml"));
FileSystem fs = FileSystem.get(conf);
System.out.println("Enter the directory name :");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Path path = new Path(br.readLine());
displayDirectoryContents(fs, path);
}
private static void displayDirectoryContents(FileSystem fs, Path rootDir) {
// TODO Auto-generated method stub
try {
FileStatus[] status = fs.listStatus(rootDir);
for (FileStatus file : status) {
if (file.isDir()) {
System.out.println("This is a directory:" + file.getPath());
displayDirectoryContents(fs, file.getPath());
} else {
System.out.println("This is a file:" + file.getPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writer a recursive function which takes a file and check if its a directory or not, if directory list out all files in it and in a for loop check if the file is a directory then recursively call or just return the list of files.
Something like this below but not exactly same (here I am returning only .java files)
private static List<File> recursiveDir(File file) {
if (!file.isDirectory()) {
// System.out.println("[" + file.getName() + "] is not a valid directory");
return null;
}
List<File> returnList = new ArrayList<File>();
File[] files = file.listFiles();
for (File f : files) {
if (!f.isDirectory()) {
if (f.getName().endsWith("java")) {
returnList.add(f);
}
} else {
returnList.addAll(recursiveDir(f));
}
}
return returnList;
}
with hdfs you can use hadoop fs -lsr .