I have a similar problem to this question, and I tried the answer that the question accepted:
File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
String content = FileUtils.readFileToString(file);
/* do somthing with content */
}
}
Only when I tried compiling, it couldn't find the variable FileUtils. Is there a java package that I have to import at the beginning of my program to use class File methods? I've never used File objects before, so I'm trying to learn to be able to work with and manipulate them. Thanks.
This is Apache Commons FileUtils
. http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
You would need to import import org.apache.commons.io.FileUtils;
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
Check here for file file utils.
Related
I want to check if a directory is exist by using the notExists(Path path, LinkOption... options) and Im confused with the LinkOption.NOFOLLOW_LINKS although after I googled I still not quite get when to use it. Here are my codes:
import java.io.*;
import java.nio.file.Files;
import java.nio.file.*;
import java.util.ArrayList;
public class Test
{
public static void main(String[] args) throws IOException
{
Path source = Paths.get("Path/Source");
Path destination = Paths.get("Path/Destination");
ArrayList<String> files = new ArrayList<String>();
int retry = 3;
// get files inside source directory
files = getFiles(source);
// move all files inside source directory
for (int j=0; j < files.size(); j++){
moveFile(source,destination,files.get(j),retry);
}
}
// move file to destination directory
public static void moveFile(Path source, Path destination, String file, int retry){
while (retry>0){
try {
// if destination path not exist, create directory
if (Files.notExists(destination, LinkOption.NOFOLLOW_LINKS)) {
// make directory
Files.createDirectories(destination);
}
// move file to destination path
Path temp = Files.move(source.resolve(file),destination.resolve(file));
// if successfully, break
if(temp != null){
break;
}
// else, retry
else {
--retry;
}
} catch (Exception e){
// retry if error occurs
--retry;
}
}
}
// get all file names in source directory
public static ArrayList<String> getFiles(Path source){
ArrayList<String> filenames = new ArrayList<String>();
File folder = new File(source.toString());
File[] listOfFiles = folder.listFiles(); // get all files inside the source directory
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
filenames.add(listOfFiles[i].getName()); // add file's name into arraylist
}
}
return filenames;
}
}
The result of using LinkOption.NOFOLLOW_LINKS and not using it are the same (The files are transferred to the destination). So, Im guessing for my case, i can ignore the Link option? also, in what situation will i be needing that? Thanks!
So, Im guessing for my case, i can ignore the Link option?
You can only follow a link if the link exists.
So if you are testing to make sure a directory doesn't exist, there are two outcomes.
it exists, so there is no need to follow the link.
it doesn't exist, so there is nothing to follow.
in what situation will i be needing that?
Did you look at my answer in the link I provided you? I tried to give a simple example.
Just for my own learning, i am trying to find all mp3 files in my music collection and finding all the tracks which do not have id3v2 tags. My code gives me information about the directory i specify, but it doesn't look for the mp3 files in subdirectories. Although i can see that it recognises the directories as i can print them out. Please see my code below. I am very sorry if the formatting of the code is not correct. I am blind and using a screen reader and the formatter on this site is not very accessible to me.
public static int numberOfUntaggedTracks(String directory) throws UnsupportedTagException, InvalidDataException, IOException {
int untaggedTracks = 0;
File f = new File(directory);
File l[] = f.listFiles();
for (File x: l) {
if (x.isHidden() || !x.canRead())
continue;
if (x.isDirectory()) {
System.out.println("testing" + x.getPath());
numberOfUntaggedTracks(x.getPath());
} else if (x.getName().endsWith(".mp3")) {
Mp3File song = new Mp3File(x.getPath());
if (song.hasId3v1Tag() == false) {
untaggedTracks++;
}
//end of else if checking for .mp3 extension
}
//end of for loop
}
return untaggedTracks;
}
FileUtils from apatche commons-io has a listFiles method that should do what you need.
The method takes two IOFileFilter instances that you can use to filter files (mp3 files in your case) and to filter sub directories (so you can control which directories to include in your search).
To make your code work just change numberOfUntaggedTracks(x.getPath()); to untaggedTracks += numberOfUntaggedTracks(x.getPath());
I am studying Java and I am not really sure the way to searching file. I would like to build the function which returning file names ( the files name should begin with star and end with .txt)
For example, in the folder we have Java source file with some file. For example, files:
1.txt
2.txt
4.txt
start.txt
star.txt
onstart.txt
starton.txt
myjava.java
Then I would like to get the start.txt, star.txt & starton.txt
I was looking for the FilenameFilter but I wasn't able to find to good way to find file. Does any one know the way to find files?
Probably the easiest way is to simple use File#listFiles(FileFilter), something like
File[] fileList = new File("/path/to/search").listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".txt");
}
});
// You'll need this import: import java.io.File;
File folder = new File("C:/Folder_Location");
// gets you the list of files at this folder
File[] listOfFiles = folder.listFiles();
// loop through each of the files looking for filenames that match
for(int i = 0; i < listOfFile.length; i++){
String filename = listOfFiles[i].getName();
if(filename.startsWith("Stuff") && listOfFiles[i].getName().endsWith("OtherStuff")){
// do something with the filename
}
}
File#getName() should return aString`, then use:
filename.startsWith(...);
filename.endsWith(...);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Appending files to a zip file with Java
I have a zip that contains a few folders in it but the important one is dir and inside that is another folder called folder and folder contains a lot of files that I need to be able to update.
I have now a dir outside of the zip called dir and in that is folder with the files i need to update in so the paths are the same. How can i update those files into the zip?
The tricky part is that dir is at the root of the zip and it contains a lot of folders not just folder but i only need to update the files in folder i can't mess with any of the files out side of folders but still in dir.
Can this be done? I know this can be done in bash using the -u modifier but I would prefer to do this with java if it's possible.
Thank you for any help with this issue
Just to be clearer
Inside Zip
/dir/folder/filestoupdate
Outside the zip
/dir/folder/filestomoveintozip
Alright well here is the final method it's the same method i pastebinned before which i actually got from the stackoverflow topic in the link #Qwe posted before but i added the path variable so that it could add files to folders inside the zip
Alright so now how to use it in my example above i wanted to add a file into a folder that was inside another folder i would do that using my setup in the question like this
private void addFilesToZip(File source, File[] files, String path){
try{
File tmpZip = File.createTempFile(source.getName(), null);
tmpZip.delete();
if(!source.renameTo(tmpZip)){
throw new Exception("Could not make temp file (" + source.getName() + ")");
}
byte[] buffer = new byte[4096];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(source));
for(int i = 0; i < files.length; i++){
InputStream in = new FileInputStream(files[i]);
out.putNextEntry(new ZipEntry(path + files[i].getName()));
for(int read = in.read(buffer); read > -1; read = in.read(buffer)){
out.write(buffer, 0, read);
}
out.closeEntry();
in.close();
}
for(ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry()){
if(!zipEntryMatch(ze.getName(), files, path)){
out.putNextEntry(ze);
for(int read = zin.read(buffer); read > -1; read = zin.read(buffer)){
out.write(buffer, 0, read);
}
out.closeEntry();
}
}
out.close();
tmpZip.delete();
}catch(Exception e){
e.printStackTrace();
}
}
private boolean zipEntryMatch(String zeName, File[] files, String path){
for(int i = 0; i < files.length; i++){
if((path + files[i].getName()).equals(zeName)){
return true;
}
}
return false;
}
Thanks for the link ended up being able to improve that method a bit so that it could add in files that weren't in the root and now i'm a happy camper :) hope this helps someone else out as well
EDIT
I worked a bit more on the method so that it could not only append to the zip but it also is able to update files within the zip
Use the method like this
File[] files = {new File("/path/to/file/to/update/in")};
addFilesToZip(new File("/path/to/zip"), files, "folder/dir/");
You wouldn't start the path (last variable) with / as that's not how it's listed in the zip entries
Unfortunately, Java can't update Zip files. The request to enhance that was submitted 14 years ago ;-)
You will need to unpack it to a temp folder, add files there and pack it back again.
Am downloading a zip file from web. It contain folders and files. Uncompressing them using ZipInputstream and ZipEntry. Zipentry.getName gives the name of file as htm/css/aaa.htm.
So I am creating new File(zipentry.getName);
But problem it is throwing an exception: File not found. I got that it is creating subfolders htm and css.
My question is: how to create a file including its sub directories, by passing above path?
Use this:
File targetFile = new File("foo/bar/phleem.css");
File parent = targetFile.getParentFile();
if (parent != null && !parent.exists() && !parent.mkdirs()) {
throw new IllegalStateException("Couldn't create dir: " + parent);
}
While you can just do file.getParentFile().mkdirs() without checking the result, it's considered a best practice to check for the return value of the operation. Hence the check for an existing directory first and then the check for successful creation (if it didn't exist yet).
Also, if the path doesn't include any parent directory, parent would be null. Check it for robustness.
Reference:
File.getParentFile()
File.exists()
File.mkdir()
File.mkdirs()
You can use Google's guava library to do it in a couple of lines with Files class:
Files.createParentDirs(file);
Files.touch(file);
https://code.google.com/p/guava-libraries/
Java NIO API Files.createDirectories
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("/folder1/folder2/folder3");
Files.createDirectories(path);
You need to create subdirectories if necessary, as you loop through the entries in the zip file.
ZipFile zipFile = new ZipFile(myZipFile);
Enumeration e = zipFile.entries();
while(e.hasMoreElements()){
ZipEntry entry = (ZipEntry)e.nextElement();
File destinationFilePath = new File(entry.getName());
destinationFilePath.getParentFile().mkdirs();
if(!entry.isDirectory()){
//code to uncompress the file
}
}
This is how I do it
static void ensureFoldersExist(File folder) {
if (!folder.exists()) {
if (!folder.mkdirs()) {
ensureFoldersExist(folder.getParentFile());
}
}
}
Looks at the file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml
isDirectoryCreated = (new File("../path_for_Directory/Directory_Name")).mkdirs();
if (!isDirectoryCreated)
{
// Directory creation failed
}