This question already has answers here:
Get resource from jar
(4 answers)
Closed 9 years ago.
Hi I am stuck with following code. I would like to get files from folder but when I export project to jar file it wont work any idea?
public String getXSDfilenames() {
String filenames= "";
try {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
path = path.substring(0, path.length()-1);
File file = new File(path+"src\\schemaFiles");
String[] files = file.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xsd");
}
});
if (file.exists()) {
for (int i = 0; i < files.length; i++) {
System.out.println(path+"src\\schemaFiles\\"+files[i]);
filenames = filenames + files[i] + newline;
}
} else {
System.out.println("No schema files founded in default folder!");
}
}
catch (Throwable e1) {
System.out.println(e1);
}
return filenames;
}
}
If you change the name of your XXX.jar file to XXX.zip, then open it in whatever Zip file utility you might have available, you can look inside the file and see 1. Whether your files are getting included in the jar at all, and if they are, 2. the actual path in which they are stored. I strongly suspect there's now src folder inside your jar.
Also, if you're NOT expecting the files to be in the jar, then you'll probably need to supply an absolute path to the files.
If they are in the jar, then check out these questions:
load file within a jar,
How to use ClassLoader.getResources() correctly?,
How do I list the files inside a JAR file?
Related
I have a simple text file called small_reports.txt that looks like:
report_2021_05_02.csv
report_2021_05_05.csv
report_2021_06_08.csv
report_2021_06_25.csv
report_2021_07_02.csv
This reported is generated with my java code and takes in each of these files from the directory /work/dir1/reports and writes them into the file combined_reports.txt and then places the txt file back into /work/dir1/reports.
My question is, for each line in small_reports.txt, find that same file (line) in /work/dir1/reports and then COPY them to a new directory called /work/dir1/smallreports?
Using Java 8 & NIO (which is really helpful and good) I have tried:
Path source = Paths.get("/work/dir1/reports/combined_reports.txt");
Path target = Paths.get("/work/dir1/smallreports/", "combined_reports.txt");
if (Files.notExists(target) && target != null) {
Files.createDirectories(Paths.get(target.toString()));
}
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
But this is just copying the actual txt file combined_reports.txt into the new directory and not the contents inside like i thought it would.
final String SOURCE_DIR = "/tmp";
final String TARGET_DIR = "/tmp/root/delme";
List<String> csvFileNames = Files.readAllLines(FileSystems.getDefault().getPath("small_reports.txt"), Charset.forName("UTF-8"));
for (String csvFileName : csvFileNames) {
Path source = Paths.get(SOURCE_DIR, csvFileName);
Path target = Paths.get(TARGET_DIR, csvFileName);
if (Files.notExists(target) && target != null) {
Files.createDirectories(Paths.get(target.toString()));
}
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
Should do it for you. Obviously change the constants appropriately
I have a folder called "all_users" in my java project under the src directory.How can I access the files(if there are any) in the all_users folder. I eventually want to loop through all the existing files in the "all_users" folder, comparing whether the file name is equal to a string i specify in the code.
Firstly, I tried File f = new File(System.getProperty("user.home")+File.pathSeparator + "all_users"); as the file object then later tried File dir = new File(TEST_PATH); Both returned false when i checked if it existed so i didn't set up the path correctly?
public class ValUtility {
static final String TEST_PATH = "./all_users/";
public static boolean validUsername(String user) {
File f = new File(System.getProperty("user.home") + File.pathSeparator + "all_users");
File dir = new File(TEST_PATH);
File[] directoryListing = f.listFiles();
System.out.println(f.exists());
System.out.println(directoryListing);
if (directoryListing != null) {
for (File child : directoryListing) {
// Do something with child
// think child is filename?
if (user.equals(child.getName())){
return false;
}
}
}
return true;
}
}
Please run...
System.out.println(System.getProperty("user.home"));
The above will inform you where you need to add a folder labeled 'all_users'. It is very unlikely that your 'user.home' property is set to your project's source file (src) folder.
hello i want to send to a class some paths of files.
I have a main folder called FoderMain which contains some
sub-folders (all different names)
Each of them contains files like this:
I want to send to a class for each sub-folder its contents(paths of files)
...and then for the next sub fodler ( until all sended )
Until now I'm reading the total number of the subfolders using this code:
public static int GetDBNumber() {
File file = new File("C:\\FoderMain");
File[] files = file.listFiles(new FileFilter(){
public boolean accept(File f) {
return f.isDirectory();}});
return files.length; } //in this example it will returns 5 sub-folders
then I'm trying to see the total files that i will send (I'm thinking to do it with a while but I'm not sure if its needed)
public static int totalSubFiles() {
File file = new File("C:\\FoderMain\\"+f.getName());
File[] files = file.listFiles(new FileFilter(){
public boolean accept(File f) {
return f.isDirectory();}});
return files.length;
}
So far i can do this if i know already the name of the files and also there have to be only one in a sub folder with this way
File file = new File("C:\\FolderMain");
File[] files = file.listFiles(new FileFilter() {
public boolean accept(File f) {
Function_test t=new Function_test(f.getPath()+"\\"+name+".text"); //if i know the name aldready & there is only one file in the sub folder
return f.isDirectory();}});
Any idea how it could work for unknown number and name?
Hope that i explained as better i could
You can use java.nio.* package and some java 8 and you can write this
String Dir = "your directory path";
Files.walk(Paths.get(Dir)).forEach(System.out::println);
this will print all the files and folder names after that you can change a path to
a file and filter however you like .
For example i have a directory contains the below files:
test.log
test.html
test.txt
I would like to know how I can make my java program pick and read only the files with .log extension.
Because the name of the file is always changing and I want to trace and read the files that have .log extension.
Any idea ?
Try following code:
File file=new File("path.log");
String name=file.toString();
String tok[]=name.split("\\.");
if(tok[tok.length-1].equals("log")){
//compute
}
Above is the core logic of checking the extension for being log. Below code is to iterate a directory and look for a file with log extension.
File file=new File("C:/Temp/");
String name,tok[];
for(File temp:file.listFiles()){
name=temp.toString();
tok=name.split("\\.");
if(tok[tok.length-1].equals("log")){
//compute
}
}
For more on File visit this link.
I use Apache Commons IO (WildcardFileFilter)
File dir = new File("/path/to/directory");
FileFilter fileFilter = new WildcardFileFilter("*.log");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++)
System.out.println(files[i]); // do something
You can use a simple regex to match the extension of the file:
if(file.toString().matches(".*\\.log"))
{
//Process the file
}
Try this
public boolean accept(File file) {
return file.getName().toLowerCase().endsWidth(".log");
}
See following snippet
Path path = Paths.get("resources/");
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(path, "*.{zip,txt}")) {
for (Path entry : dirStream) {
System.out.printf("%-5s: %s%n", "entry", entry.getFileName());
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
For more details have a look into this full example:
https://github.com/jugsaar/jugsaar-meeting-9/blob/master/talks/java-nio2/src/main/java/de/jugsaar/meeting9/nio2/directorystream/DirectoryStreamGlobbingPatternDemo.java
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Copying files from one directory to another in Java
How can I move all files from one folder to other folder with java?
I'm using this code:
import java.io.File;
public class Vlad {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// File (or directory) to be moved
File file = new File("C:\\Users\\i074924\\Desktop\\Test\\vlad.txt");
// Destination directory
File dir = new File("C:\\Users\\i074924\\Desktop\\Test2");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
System.out.print("not good");
}
}
}
but it is working only for one specific file.
thanks!!!
By using org.apache.commons.io.FileUtils class
moveDirectory(File srcDir, File destDir) we can move whole directory
If a File object points to a folder you can iterate over it's content
File dir1 = new File("C:\\Users\\i074924\\Desktop\\Test");
if(dir1.isDirectory()) {
File[] content = dir1.listFiles();
for(int i = 0; i < content.length; i++) {
//move content[i]
}
}
Since Java 1.7 there is java.nio.file.Files which offers operations to work with files and directories. Especially the move, copy and walkFileTree functions might be of interest to you.
You can rename the directory itself.
You can iterate over files in directory and rename them one-by-one. If directory can contain subdirectories you have to do this recursively.
you can use utility like Apache FileUtils that already does all this.