I'm trying to load classes from tree structure similar to JavaEE web application. So I have directory which contains compiled classes (/classes) and sibling directory with libraries (/lib). In classes package structure I have compiled class com.test.Test.class with simple logic:
package com.test;
import org.json.JSONException;
import org.json.JSONObject;
import com.test.GameObjectState;
public class Test extends Thread {
#Override
public void run() {
JSONObject json = new JSONObject();
try {
json.put("state", GameObjectState.REMOVED);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(json.toString());
}
}
And here's my main:
ClassLoader classLoader = ClassLoaderFactory.createClassLoader(repository);
Class<?> testClass = classLoader.loadClass("com.test.Test");
Thread t = (Thread) testClass.newInstance();
t.start();
My ClassLoader implementation follows the delegation model. During context init finally JSONObject & JSONException will be scanned and found in lib/java-json.jar (matching corresponding JarEntry binary name inside). When JarEntry found - creates InputStream to load data in buffer to define class.
JSONException loaded successfully while JSONObject failed on ClassFormatError. Magic is that I've extracted JSONObject in /classes directory manually from java-json.jar and no ClassFormatError has been thrown, JSONObject created and output printed successfully. Probably should note that JSONObject has inner/nested classes compiled in library.
And here's my classloader
public class WebAppClassLoader extends URLClassLoader {
private static final String CLASS_FILE_SUFFIX = ".class";
private static final String JAR_FILE_SUFFIX = ".jar";
private static final String CLASS_NOT_FOUND = "Class %s not found";
private File classesDirectory;
private Map<String, Class<?>> classes;
public WebAppClassLoader(File classesDirectory, URL[] urls) {
super(urls);
this.classesDirectory = classesDirectory;
this.classes = new ConcurrentHashMap<String, Class<?>>();
}
public static WebAppClassLoader newInstance(File classesDirectory, File libDirectory) throws IOException {
File[] jars = libDirectory.listFiles(new JarFilter());
Set<URL> jarUrls = new HashSet<URL>();
for(File jar : jars) {
jarUrls.add(jar.toURI().toURL());
}
return new WebAppClassLoader(classesDirectory, jarUrls.toArray(new URL[jarUrls.size()]));
}
protected static class DirectoryFilter implements FileFilter {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
}
protected static class ClassFilter implements FileFilter {
#Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(CLASS_FILE_SUFFIX);
}
}
protected static class JarFilter implements FileFilter {
#Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(JAR_FILE_SUFFIX);
}
}
#Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> result = null;
byte[] buffer = null;
try {
buffer = scanClasses(classesDirectory, asPathName(name));
if(buffer == null) {
buffer = scanLib(asPathName(name).replace('\\', '/'));
}
if(buffer != null) {
result = defineClass(name, buffer, 0, buffer.length);
classes.put(name, result);
}
} catch(IOException e) {
e.printStackTrace();
}
if(result == null) {
String error = String.format(CLASS_NOT_FOUND, name);
throw new ClassNotFoundException(error);
}
return result;
}
private byte[] scanClasses(File file, String path) throws IOException {
byte[] result = null;
File[] directories = file.listFiles(new DirectoryFilter());
File[] classes = file.listFiles(new ClassFilter());
for(File classFile : classes) {
if(classFile.getAbsolutePath().endsWith(path)) {
InputStream input = new FileInputStream(classFile);
input.read(result = new byte[input.available()]);
input.close();
break;
}
}
if(result == null) {
for(File directory : directories) {
result = scanClasses(directory, path);
if(result != null) {
break;
}
}
}
return result;
}
private byte[] scanLib(String path) throws IOException {
byte[] result = null;
for(URL url : getURLs()) urlLoop:{
File file = new File(url.getFile());
JarFile jarFile = new JarFile(file);
try {
Enumeration<JarEntry> entries = jarFile.entries();
while(entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if(entry.getName().endsWith(path)) {
InputStream input = jarFile.getInputStream(entry);
input.read(result = new byte[input.available()]);
break urlLoop;
}
}
}finally {
jarFile.close();
}
}
return result;
}
#Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
Class<?> result = null;
if(classes.containsKey(name)) {
result = classes.get(name);
}else{
result = super.loadClass(name);
}
return result;
}
private static String asPathName(String binaryName) {
return binaryName.replace('.', '\\').concat(CLASS_FILE_SUFFIX);
}
}
Thanks
Related
I don't know why the isFile() of the element f in the files list traversed by the for loop in the FileInit class in the code below is always false.false. But if delete the content related to FileItem, it will return to normal.It's kind of weird to me, and I didn't find a targeted answer. It might be some peculiarity of Java.A cloud disk project is used to learn Java, using Google's Gson library.
public class FileInit {
String path;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
//Query file method, will return a list containing file information
public String queryFiles() throws NoSuchAlgorithmException, IOException {
//Query the path and build a File collection
File file = new File(path);
File[] files = file.listFiles();
//Build a List to store the converted FileItem
List<FileItem> fileItems = new ArrayList<>();
//Traversing files to make judgments
for (File f:files){
FileItem fileItem = new FileItem(f);
fileItem.printFile();
fileItems.add(fileItem);
}
Gson gson = new Gson();
return gson.toJson(fileItems);
}
//formatted output
public void printFiles(String files){
Gson gson = new Gson();
Type type = new TypeToken<List<FileItem>>(){}.getType();
List<FileItem> fileItems = gson.fromJson(files, type);
// Format output file list
int count = 0;
for (FileItem f :fileItems ) {
String name;
if (f.getFileType()==null){
name = f.getFileName() + "/";
}else {
name = f.getFileName();
}
System.out.printf("%-40s", name);
count++;
if (count % 3 == 0) {
System.out.println();
}
}
System.out.println();
}
//Change directory command
public void changeDic(String addPath){
File fileDic1 = new File(path+addPath);
File fileDic2 = new File(addPath);
if (addPath.equals("..")) {
File parent = new File(path).getParentFile();
if (parent != null) {
this.path = parent.getPath();
}else{
System.out.println("Parent directory does not exist");
}
}
else {
if (fileDic1.exists()){
this.path = path+addPath;
} else if (fileDic2.exists()) {
this.path = addPath;
}else{
System.out.println("Illegal input path");
}
}
}
}
public class FileItem {
private String fileName;
private String fileHash;
private String filePath;
private long fileLength;
private String fileType;
//Construction method of FileItem
/*
Build a construction method that only needs fileName and filePath, and judge whether to calculate the hash value, file size, and file type according to the folder or file
*/
public FileItem(String fileName,String filePath) {
this.fileName = fileName;
this.filePath = filePath;
File file =new File(this.filePath+"/"+this.fileName);
if (file.isFile()){
try {
//Get the file size through the file built-in method
this.fileLength = file.length();
// Define a regular expression for extracting the suffix of the file name
String regex = "\\.(\\w+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(fileName);
// If the match is successful
if (matcher.find()) {
// Get the suffix of the file name
this.fileType = matcher.group(1);
}else{
this.fileType = null;
}
//Calculate the Hash value of the file by calling the FileHash method
this.fileHash=FileHash(file.getPath());
System.out.printf(fileHash);
System.out.print("\n");
} catch (NoSuchAlgorithmException | IOException e) {
throw new RuntimeException(e);
}
}else{
this.fileName=fileName;
this.fileLength=0;
this.fileType = null;
this.fileHash=null;
}
}
//Build a constructor that only needs a json file
public FileItem(String json){
Gson gson = new Gson();
FileItem fileItem = gson.fromJson(json,FileItem.class);
this.fileName=fileItem.getFileName();
this.filePath=fileItem.getFilePath();
this.fileHash=fileItem.getFileHash();
this.fileLength=fileItem.getFileLength();
this.fileType=fileItem.getFileType();
}
//Realize mutual conversion between FileItem and File class
public File toFile(){
return new File(this.filePath+"/"+this.fileName);
}
public FileItem(File file) throws NoSuchAlgorithmException, IOException {
FileItem fileItem = new FileItem(file.getName(),file.getPath());
this.fileName=fileItem.getFileName();
this.filePath=fileItem.getFilePath();
this.fileHash=fileItem.getFileHash();
this.fileLength=fileItem.getFileLength();
this.fileType=fileItem.getFileType();
}
//Display FileItem related information
public void printFile(){
if (fileType==null){
System.out.println(fileName+"是文件夹");
}else {
System.out.println(fileName+"是"+fileType+"文件");
}
double fileLenOp=(double)fileLength;
//Different file sizes use different output methods
if(fileLength<=1024*1024){
System.out.printf("file size is:%.3fKB\n",fileLenOp/1024);
} else if ((fileLength<1024*1024*1024)) {
System.out.printf("file size is:%.3fMB\n",fileLenOp/1024/1024);
}else {
System.out.printf("file size is:%.3fGB\n",fileLenOp/1024/1024/1024);
}
System.out.println("file hash is:"+fileHash);
}
//Getter and Setter methods for FileItem
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileHash() {
return fileHash;
}
public void setFileHash(String fileHash) {
this.fileHash = fileHash;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public long getFileLength() {
return fileLength;
}
public void setFileLength(long fileLength) {
this.fileLength = fileLength;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
}
I try to query the file information in a folder by using the methods related to the File class. And return them as a collection. Then realize the conversion of the File class and the FileItem class by traversing this collection to form a new FileItem class collection , so that it can be converted into Json format data for network transmission. However, all fileitems in the generated FileItem collection are judged as folders. And if you comment out the FileItem related content, the judgment of File will be normal, but if you don’t do this , the judgment of File will always remain false.
I have a custom ListView that uses an object class for its data. The users can add new items to the listview, the arraylist is then saved in SharedPreferences. However, I also want to save each individual item so that I can use it in another Expandable ListView, how could I create a file for each individual item the user creates, or perhaps there is a better why to do it? Thanks in advance. Here is the object class:
public class Item implements Serializable{
String homework, date, classes;
public Item(String homework, String date, String classes){
this.homework = homework;
this.date = date;
this.classes = classes;
}
public String getHomework(){
return homework;
}
public String getDate(){
return date;
}
public String getClasses(){
return classes;
}
}
Why not use a database?There is a bit of setting up, but after the initial set up writing/reading data is very easy.
https://developer.android.com/training/basics/data-storage/databases.html
An example of serialize-deserialize class
public final class Serialize
{
private static final String className = Serialize.class.getName();
public static void save(Object saveThis, String serializeFileName, Context context)
{
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
if(saveThis != null)
{
fos = context.openFileOutput(serializeFileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(saveThis);
}
}
catch(Throwable t)
{
//log it
}
finally
{
if(oos != null)
{
try{oos.close();}catch(Throwable t){}
}
if(fos != null)
{
try{fos.close();}catch(Throwable t){}
}
}
}
public static Object read(String serializeFileName, Context context)
{
FileInputStream fis = null;
ObjectInputStream ois = null;
Object readThis = null;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && file.exists())
{
fis = context.openFileInput(serializeFileName);
ois = new ObjectInputStream(fis);
readThis = ois.readObject();
}
}
catch(Throwable t)
{
//log it
}
finally
{
if(ois != null)
{
try{ois.close();}catch(Throwable t){}
}
if(fis != null)
{
try{fis.close();}catch(Throwable t){}
}
}
return readThis;
}
public static boolean delete(String serializeFileName, Context context)
{
boolean deleted = false;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && (file.exists()))
{
deleted = file.delete();
}
}
catch(Throwable t)
{
//log it
}
return deleted;
}
public static boolean exist(String serializeFileName, Context context)
{
boolean exist = false;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && (file.exists()))
{
exist = true;
}
}
catch(Throwable t)
{
//log it
}
return exist;
}
}
Use the save method to save the serializable object in a file and the read method to read it.
I am developing a voice-based app in android and facing some problems please see below code,
Java File 1
file = .wav file
public static AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException {
return getAudioInputStreamImpl(file);
}
private static AudioInputStream getAudioInputStreamImpl(Object source) throws UnsupportedAudioFileException, IOException {
GetAudioInputStreamAudioFileReaderAction action = new GetAudioInputStreamAudioFileReaderAction(source);
doAudioFileReaderIteration(action);
AudioInputStream audioInputStream = action.getAudioInputStream();
if (audioInputStream != null) {
return audioInputStream;
}
throw new UnsupportedAudioFileException("format not supported");
}
private static void doAudioFileReaderIteration(AudioFileReaderAction action) throws IOException {
Iterator audioFileReaders = TAudioConfig.getAudioFileReaders();
boolean bCompleted = false;
while (audioFileReaders.hasNext() && !bCompleted) {
AudioFileReader audioFileReader = (AudioFileReader) audioFileReaders.next();
bCompleted = action.handleAudioFileReader(audioFileReader);
}
}
Java file 2 (TAudioConfig)
public static synchronized Iterator<AudioFileReader> getAudioFileReaders() {
Iterator<AudioFileReader> it;
synchronized (TAudioConfig.class) {
it = getAudioFileReadersImpl().iterator();
}
return it;
}
private static synchronized Set<AudioFileReader> getAudioFileReadersImpl() {
Set<AudioFileReader> set;
synchronized (TAudioConfig.class) {
if (sm_audioFileReaders == null) {
sm_audioFileReaders = new ArraySet();
registerAudioFileReaders();
}
set = sm_audioFileReaders;
}
return set;
}
private static void registerAudioFileReaders() {
TInit.registerClasses(AudioFileReader.class, new C00001());
}
Java File 3 (TInit)
public static void registerClasses(Class providerClass, ProviderRegistrationAction action) {
Iterator providers = Service.providers(providerClass);
if (providers != null) {
while (providers.hasNext()) {
try {
action.register(providers.next());
} catch (Throwable e) {
}
}
}
}
Java File 4 (Service)
public static Iterator<?> providers(Class<?> cls) {
String strFullName = "com/example/voiceautomator/AudioFileReader.class";
Iterator<?> iterator = createInstancesList(strFullName).iterator();
return iterator;
}
private static List<Object> createInstancesList(String strFullName) {
List<Object> providers = new ArrayList<Object>();
Iterator<?> classNames = createClassNames(strFullName);
if (classNames != null) {
while (classNames.hasNext()) {
String strClassName = (String) classNames.next();
try {
Class<?> cls = Class.forName(strClassName, REVERSE_ORDER, ClassLoader.getSystemClassLoader());
providers.add(0, cls.newInstance());
} catch (Throwable e) {
}
}
}
return providers;
}
private static Iterator<String> createClassNames(String strFullName) {
Set<String> providers = new ArraySet<String>();
Enumeration<?> configs = null;
try {
configs = Service.class.getClassLoader().getSystemResources(strFullName);
} catch (Throwable e) {
}
if (configs != null) {
while (configs.hasMoreElements()) {
URL configFileUrl = (URL) configs.nextElement();
InputStream input = null;
try {
input = configFileUrl.openStream();
} catch (Throwable e2) {
}
if (input != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
try {
for (String strLine = reader.readLine(); strLine != null; strLine = reader.readLine()) {
strLine = strLine.trim();
int nPos = strLine.indexOf(35);
if (nPos >= 0) {
strLine = strLine.substring(0, nPos);
}
if (strLine.length() > 0) {
providers.add(strLine);
}
}
} catch (Throwable e22) {
}
}
}
}
Iterator<String> iterator = providers.iterator();
return iterator;
}
getClassLoader().getSystemResources in the Java File 4 (Service) gives me TwoEnumerationsInOne and configs.hasMoreElements() gives false so not able to go into while loop.
AudioFileReader.java is included in the package
Please guide me to resolve this issue?
Please don't forget I am working on this code in an android project
Please see the value of configs here
http://capsicumtech.in/Screenshot_1.png
Thanks in advance.
I try to get the list of files from classpath (web-inf/classes/dir).
Enumeration<URL> en = getClass().getClassLoader().getResources("dir");
However, instead of elements in this folder, the only element is the folder itself. Is there a way I can get the list of files, or the only way is to access file one by one. Because when I try to refer to some file in the same folder, I can easily access its contents.
You can't browse a directory on the classpath recursively.
See this post: How to use ClassLoader.getResources() correctly?
If you know you're looking at a JAR file however, you might open it directly as an archive and browse the files.
Somebody came up with a useful answer for this question: Get all of the Classes in the Classpath
You could adapt this code to browse through all JAR files and directories on your classpath and apply some filter for your directory name yourself. The example will list all classes from the gnu.trove.* package:
import java.io.File;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class Test
{
public static void main(String[] args)
{
final String dirname = "gnu.trove.";
findClasses(new Visitor<String>() {
#Override
public boolean visit(String classname)
{
if (classname.startsWith(dirname)) {
System.out.println(classname);
}
return true;
}
});
}
public interface Visitor<T>
{
public boolean visit(T t);
}
public static void findClasses(Visitor<String> visitor)
{
String classpath = System.getProperty("java.class.path");
String[] paths = classpath.split(System.getProperty("path.separator"));
String javaHome = System.getProperty("java.home");
File file = new File(javaHome + File.separator + "lib");
if (file.exists()) {
findClasses(file, file, true, visitor);
}
for (String path : paths) {
file = new File(path);
if (file.exists()) {
findClasses(file, file, true, visitor);
}
}
}
private static boolean findClasses(File root, File file,
boolean includeJars, Visitor<String> visitor)
{
if (file.isDirectory()) {
for (File child : file.listFiles()) {
if (!findClasses(root, child, includeJars, visitor)) {
return false;
}
}
} else {
if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
JarFile jar = null;
try {
jar = new JarFile(file);
} catch (Exception ex) {
}
if (jar != null) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
int extIndex = name.lastIndexOf(".class");
if (extIndex > 0) {
if (!visitor.visit(name.substring(0, extIndex)
.replace("/", "."))) {
return false;
}
}
}
}
} else if (file.getName().toLowerCase().endsWith(".class")) {
if (!visitor.visit(createClassName(root, file))) {
return false;
}
}
}
return true;
}
private static String createClassName(File root, File file)
{
StringBuffer sb = new StringBuffer();
String fileName = file.getName();
sb.append(fileName.substring(0, fileName.lastIndexOf(".class")));
file = file.getParentFile();
while (file != null && !file.equals(root)) {
sb.insert(0, '.').insert(0, file.getName());
file = file.getParentFile();
}
return sb.toString();
}
}
Here is some code for ignoring JAR files and just going through the files on directories on your classpath:
import java.io.File;
public class Test
{
public static void main(String[] args)
{
findClasses(new Visitor<String>() {
#Override
public boolean visit(String classname)
{
// apply your filtering here
System.out.println(classname);
return true;
}
});
}
public interface Visitor<T>
{
public boolean visit(T t);
}
public static void findClasses(Visitor<String> visitor)
{
String classpath = System.getProperty("java.class.path");
String[] paths = classpath.split(System.getProperty("path.separator"));
for (String path : paths) {
File file = new File(path);
// Ignore JAR files, just go through directories on the classpath
if (file.isFile()) {
continue;
}
findFiles(file, file, visitor);
}
}
private static boolean findFiles(File root, File file,
Visitor<String> visitor)
{
if (file.isDirectory()) {
for (File child : file.listFiles()) {
if (!findFiles(root, child, visitor)) {
return false;
}
}
} else {
if (!visitor.visit(createRelativePath(root, file))) {
return false;
}
}
return true;
}
private static String createRelativePath(File root, File file)
{
StringBuffer sb = new StringBuffer();
sb.append(file.getName());
file = file.getParentFile();
while (file != null && !file.equals(root)) {
sb.insert(0, '/').insert(0, file.getName());
file = file.getParentFile();
}
return sb.toString();
}
}
I know how to copy a file from one directory to another, what I would like help on is copy a file with .jpg or .doc extension.
So for example.
Copy all files from D:/Pictures/Holidays
Scanning all folders in the above path and transfer all jpg's to a destination provided.
This works, but the file 'copy(File file, File outputFolder)' method could be enhanced for large files:
package net.bpfurtado.copyfiles;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFilesFromType
{
public static void main(String[] args)
{
new CopyFilesFromType().copy("jpg", "C:\\Users\\BrunoFurtado\\Pictures", "c:/temp/photos");
}
private FileTypeOrFolderFilter filter = null;
private void copy(final String fileType, String fromPath, String outputPath)
{
filter = new FileTypeOrFolderFilter(fileType);
File currentFolder = new File(fromPath);
File outputFolder = new File(outputPath);
scanFolder(fileType, currentFolder, outputFolder);
}
private void scanFolder(final String fileType, File currentFolder, File outputFolder)
{
System.out.println("Scanning folder [" + currentFolder + "]...");
File[] files = currentFolder.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
scanFolder(fileType, file, outputFolder);
} else {
copy(file, outputFolder);
}
}
}
private void copy(File file, File outputFolder)
{
try {
System.out.println("\tCopying [" + file + "] to folder [" + outputFolder + "]...");
InputStream input = new FileInputStream(file);
OutputStream out = new FileOutputStream(new File(outputFolder + File.separator + file.getName()));
byte data[] = new byte[input.available()];
input.read(data);
out.write(data);
out.flush();
out.close();
input.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private final class FileTypeOrFolderFilter implements FileFilter
{
private final String fileType;
private FileTypeOrFolderFilter(String fileType)
{
this.fileType = fileType;
}
public boolean accept(File pathname)
{
return pathname.getName().endsWith("." + fileType) || pathname.isDirectory();
}
}
}
Use a FileFilter when listing files.
In this case, the filter would select directories and any file type of interest.
Here is a quick example (crudely hacked out of another project) of gaining a list of types of files in a directory structure.
import java.io.*;
import java.util.ArrayList;
class ListFiles {
public static void populateFiles(File file, ArrayList<File> files, FileFilter filter) {
File[] all = file.listFiles(filter);
for (File f : all) {
if (f.isDirectory()) {
populateFiles(f,files,filter);
} else {
files.add(f);
}
}
}
public static void main(String[] args) throws Exception {
String[] types = {
"java",
"class"
};
FileFilter filter = new FileTypesFilter(types);
File f = new File("..");
ArrayList<File> files = new ArrayList<File>();
populateFiles(f, files, filter);
for (File file : files) {
System.out.println(file);
}
}
}
class FileTypesFilter implements FileFilter {
String[] types;
FileTypesFilter(String[] types) {
this.types = types;
}
public boolean accept(File f) {
if (f.isDirectory()) return true;
for (String type : types) {
if (f.getName().endsWith(type)) return true;
}
return false;
}
}
Use following file walker tree class to do that
static class TreeCopier implements FileVisitor<Path> {
private final Path source;
private final Path target;
private final boolean preserve;
private String []fileTypes;
TreeCopier(Path source, Path target, boolean preserve, String []types) {
this.source = source;
this.target = target;
this.preserve = preserve;
this.fileTypes = types;
}
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
// before visiting entries in a directory we copy the directory
// (okay if directory already exists).
CopyOption[] options = (preserve)
? new CopyOption[]{COPY_ATTRIBUTES} : new CopyOption[0];
Path newdir = target.resolve(source.relativize(dir));
try {
Files.copy(dir, newdir, options);
} catch (FileAlreadyExistsException x) {
// ignore
} catch (IOException x) {
System.err.format("Unable to create: %s: %s%n", newdir, x);
return SKIP_SUBTREE;
}
return CONTINUE;
}
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
String fileName = file.toFile().getName();
boolean correctType = false;
for(String t: fileTypes) {
if(fileName.endsWith(t)){
correctType = true;
break;
}
}
if(correctType)
copyFile(file, target.resolve(source.relativize(file)), preserve);
return CONTINUE;
}
#Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
// fix up modification time of directory when done
if (exc == null && preserve) {
Path newdir = target.resolve(source.relativize(dir));
try {
FileTime time = Files.getLastModifiedTime(dir);
Files.setLastModifiedTime(newdir, time);
} catch (IOException x) {
System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);
}
}
return CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
if (exc instanceof FileSystemLoopException) {
System.err.println("cycle detected: " + file);
} else {
System.err.format("Unable to copy: %s: %s%n", file, exc);
}
return CONTINUE;
}
static void copyFile(Path source, Path target, boolean preserve) {
CopyOption[] options = (preserve)
? new CopyOption[]{COPY_ATTRIBUTES, REPLACE_EXISTING}
: new CopyOption[]{REPLACE_EXISTING};
if (Files.notExists(target)) {
try {
Files.copy(source, target, options);
} catch (IOException x) {
System.err.format("Unable to copy: %s: %s%n", source, x);
}
}
}
}
and call it using following two lines
String []types = {".java", ".form"};
TreeCopier tc = new TreeCopier(src.toPath(), dest.toPath(), false, types);
Files.walkFileTree(src.toPath(), tc);
.java and .form file types are not omitted to copy and passed as String array parameter, src.toPath() and dest.toPath() are source and destination paths, false is used to specify not to preserve previous files and overwrite them
if you want reverse that is to consider only these remove not and use as
if(!correctType)
Take a look at the listFiles methods from the File class:
Link 1
Link 2
You could try this code:
public class MyFiler implements FileNameFilter{
bool accept(File file, String name){
if(name.matches("*.jpg");
}
}
public void MassCopy(){
ArrayList<File> filesToCopy = new ArrayList<File>();
File sourceDirectory = new File("D:/Pictures/Holidays");
String[] toCopy = sourceDirectory.list(new MyFilter());
for(String file : toCopy){
copyFileToDestination(file);
}
}