I'm having real difficulties figuring out how this needs to be coded without using FileUtils import. I have found thousands of tutorials on how to move files to empty folders, that's easy. The difficulty is finding out how Java can move files to directories that already have files in the folder. As I understand it the REPLACE_EXISTING parameter means it will overwrite identical file names if detected in the destination directory, but the directory doesn't have a file with a matching name of the file I'm attempting to copy/move. What am I missing? How can I make this happen?
java.nio.file.DirectoryNotEmptyException occuring.
enter code here
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Move {
static File source = new File("sourcefolderhere");
static File destination = new File("destfolderhere");
public static void move(File src, File dest) throws IOException {
Files.move(src.toPath().toAbsolutePath(), dest.toPath().toAbsolutePath(),
StandardCopyOption.REPLACE_EXISTING);
}
public static void main(String[] args) throws IOException {
try {
if(source.isDirectory() && destination.isDirectory()) {
File[] content = source.listFiles();
for(int i = 0; i < content.length; i++) {
System.out.println(content[i]);
move(source, destination);
}
}
else if (!destination.isDirectory()){
System.out.println("create folder here");
destination.mkdir();
File[] content = source.listFiles();
for(int i = 0; i < content.length; i++) {
move(source, destination);
}
}
}
catch(Exception ex) { System.out.println(ex);
}
finally {
}
}
}
I tried the code in IDE File.move method with parameter StandardCopyOption.REPLACE_EXISTING works only if you have file in the destination folder. otherwise use File.move the normal way. I have also modified your code a little just to avoid code duplication.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
public class Move {
static File source = new File("sourcefolderhere");
static File destination = new File("destfolderhere");
public static void move(File src, File dest) throws IOException {
System.out.println(src.getName());
if(isExist(src.getName()))
Files.move(src.toPath().toAbsolutePath(), Paths.get(destination.getAbsolutePath()+File.separator+src.getName()) , StandardCopyOption.REPLACE_EXISTING);
else
Files.move(src.toPath().toAbsolutePath(), Paths.get(destination.getAbsolutePath()+File.separator+src.getName()));
}
public static boolean isExist(String souceFileName){
//If you are not using java 8 code
/*String[] destFiles = destination.list();
for(String fileName : destFiles){
if(souceFileName.equals(fileName))
return true;
}
return false;*/
return Arrays.stream(destination.list())
.anyMatch(fileName -> fileName.equals(souceFileName));
}
public static void main(String[] args) throws IOException {
try {
if(!source.isDirectory())
throw new IllegalArgumentException("Source Folder doesn't Exist");
if(!destination.exists())
destination.mkdir();
if (source.isDirectory() && destination.isDirectory()) {
File[] content = source.listFiles();
for (int i = 0; i < content.length; i++) {
System.out.println(content[i]);
move(content[i], destination);
}
}
} catch (Exception ex) {
System.out.println(ex);
} finally {
}
}
}```
Related
I have got this class for loading blue images, which works fine in Eclipse but not in the exported jar. How can I access all the blue images in the folder (directory) called "blue" without knowing the names of the images?
public class Blue
{
public static void read() throws Exception
{
File directoryBlueImages = new File(
Blue.class.getResource("blue").getFile());
String[] blueImages = directoryBlueImages.list();
List<BufferedImage> blueImagesList = new ArrayList<>();
for (String blueImage : java.util.Objects.requireNonNull(blueImages))
{
blueImagesList.add(ImageIO
.read(Blue.class.getResourceAsStream("blue/" + blueImage)));
}
ApplicationImages.setBlueImages(blueImagesList);
}
}
UPDATE
I have tried this, but it does not work either. I am getting a NullPointer exception. I tried "/blue" and "blue" and even ".blue".
import java.awt.image.BufferedImage;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import vokabeltrainer.ApplicationImages;
public class Blue
{
public static void read() throws Exception
{
List<BufferedImage> blueImagesList = new ArrayList<>();
try (Stream<Path> pathStream = Files.walk(Paths.get(Blue.class
.getClassLoader().getResource("blue").toURI().toURL().getPath()))
.filter(Files::isRegularFile))
{
for (Path file : (Iterable<Path>) pathStream::iterator)
{
blueImagesList.add(ImageIO
.read(Blue.class.getResourceAsStream(file.toString())));
;
}
}
ApplicationImages.setBlueImages(blueImagesList);
}
}
I adapted an answer from How to list the files inside a JAR file?
First I distinguish wether I am running from jar or Eclipse:
try
{
Blue.readZip(); // when inside jar
}
catch (Exception e)
{
try
{
Blue.read(); // during development
}
catch (Exception e1)
{
System.out.println("Could not read blue.");
e1.printStackTrace();
}
}
Then class Blue looks like this:
public class Blue
{
private static List<BufferedImage> blueImagesList = new ArrayList<>();
public static void read() throws Exception
{
File directoryBlueImages = new File(
Blue.class.getResource("blue").getFile());
String[] blueImages = directoryBlueImages.list();
for (String blueImage : java.util.Objects.requireNonNull(blueImages))
{
blueImagesList.add(ImageIO
.read(Blue.class.getResourceAsStream("blue/" + blueImage)));
}
ApplicationImages.setBlueImages(blueImagesList);
}
public static void readZip() throws Exception
{
CodeSource src = Blue.class.getProtectionDomain().getCodeSource();
if (src != null)
{
URL jar = src.getLocation();
ZipFile zipFile = new ZipFile(jar.getFile());
ZipInputStream zip = new ZipInputStream(jar.openStream());
while (true)
{
ZipEntry ze = zip.getNextEntry();
if (ze == null)
break;
String name = ze.getName();
if (name.startsWith("vokabeltrainer/resources/blue/"))
{
blueImagesList.add(ImageIO.read(zipFile.getInputStream(ze)));
}
}
}
else
{
throw new IOException("can not find code source for blue images");
}
ApplicationImages.setBlueImages(blueImagesList);
}
}
I have the following code seen below, this code looks through a directory and then prints all of the different file names. Now my question is, how would I go about changing my code, so that it would also print out all of the content within the files which it finds/prints? As an example, lets say the code finds 3 files in the directory, then it would print out all the content within those 3 files.
import java.io.File;
import java.io.IOException;
public class EScan {
static String usernamePc = System.getProperty("user.name");
final static File foldersPc = new File("/Users/" + usernamePc + "/Library/Mail/V2");
public static void main(String[] args) throws IOException {
listFilesForFolder(foldersPc);
}
public static void listFilesForFolder(final File foldersPc) throws IOException {
for (final File fileEntry : foldersPc.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
I tested it before posting. it is working.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* #author EdwinAdeola
*/
public class TestPrintAllFiles {
public static void main(String[] args) {
//Accessing the folder path
File myFolder = new File("C:\\Intel");
File[] listOfFiles = myFolder.listFiles();
String fileName, line = null;
BufferedReader br;
//For each loop to print the content of each file
for (File eachFile : listOfFiles) {
if (eachFile.isFile()) {
try {
//System.out.println(eachFile.getName());
fileName = eachFile.getAbsolutePath();
br = new BufferedReader(new FileReader(fileName));
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
You may use Scanner to read the contents of the file
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
System.out.println(s);
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
You can try one more way if you find suitable :
package com.grs.stackOverFlow.pack10;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
public class EScan {
public static void main(String[] args) throws IOException {
File dir=new File("C:/your drive/");
List<File> files = Arrays.asList(dir.listFiles(f->f.isFile()));
//if you want you can filter files like f->f.getName().endsWtih(".csv")
for(File f: files){
List<String> lines = Files.readAllLines(f.toPath(),Charset.defaultCharset());
//processing line
lines.forEach(System.out::println);
}
}
}
Above code can me exploited in number of ways like processing line can be modified to add quotes around lines as below:
lines.stream().map(t-> "'" + t+"'").forEach(System.out::println);
Or print only error messages lines
lines.stream().filter(l->l.contains("error")).forEach(System.out::println);
Above codes and variations are tested.
Description : I am trying to parse my main directory to find all the files of type ".jpg" and my code is able to return all the files that are needed. example "C:\Ravi\Sources", in this directory i have mixed files of .xml, .jpg, .gif, now i am also having sub folders inside this directory but i don't know
how to modify my code to check for sub-directories as well.
Expertise help is required here :
Code Snippet :
enter code here
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.PrintStream;
public class Subdirectory {
static File f = new File("C:\\Users\\kasharma\\Desktop\\Travelocity R8.3_8.3.0.apk\\res");// File f will represent the folder....
static String[] extensions = new String[]{"png", "jpg", "gif" }; // Declaring array of supported filters...
// Applying filter to identify images based on their extensions...
static FilenameFilter Image_Filter = new FilenameFilter() {
public boolean accept(File f, String name)
{
for(String ext: extensions){
if(name.endsWith("."+ ext)){
return(true);
}
}
return(false);
}
};
public static void goThroughDirectories(String path)
{
}
public static void main(String[] args) {
String path = "C:\\Users\\kasharma\\Desktop\\Travelocity R8.3_8.3.0.apk\\res";
for (File file : f.listFiles(Image_Filter))
{
if (f.isDirectory()) goThroughDirectories(path+f.getName());
BufferedImage img = null;
try {
img = ImageIO.read(file);
System.out.println("image "+ file.getName());
} catch (IOException e) {
// handle errors here
}
}
}
}
Look at java.nio.files, especially the walkFileTree(...) and find(...) methods. Java 8 includes a builtin capability for this.
Using walkFileTree:
public static void main(String[] args) throws Exception
{
Path p = Paths.get("D:/");
Files.walkFileTree(p,
new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{
System.out.println(file.toFile().getName());
return FileVisitResult.CONTINUE;
}
}
);
}
Here's an even better solution using find that returns a lazily populated stream and filters for .jpg at the same time:
public static void main(String[] args) throws Exception
{
Path p = Paths.get("D:/");
Files
.find(
p,
Integer.MAX_VALUE,
(path,attr) -> path.toString().endsWith(".jpg"))
.forEach(path -> System.out.println(path.toFile().getName()));
}
This will give you the idea. This is pseudocode.
void goThroughDirectories(String path)
{
for(File f : fileList)
{
if(f.isDirectory()) goThroughDirectories(path+f.getName());
else {
//do something
}
}
}
I want to read 10% of the files from a directory which contains sub-directories and want to write files as in respective sub-directories.I am currently able to read 10% random files using random method and write them in a folder but the code doesn't work for sub-directories.
My code is:
'
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class CreateSampleDocuments
{
String text="";
String str="";
Map<Integer, File> selection = new HashMap<Integer, File>(1000);
public void readSampleFiles(File files[])throws IOException
{
while (selection.size() <= files.length/5)
{
int value = (int)Math.round(Math.random() * files.length);
if (!selection.containsKey(value))
{
selection.put(value, files[value]);
}
}
for (File file : selection.values())
{
if(file.isFile())
{
String name = UUID.randomUUID().toString();
PrintWriter pw=new PrintWriter("/home/gauge/Documents/Docs/Misc"+"/"+name);
BufferedReader br=new BufferedReader(new FileReader(file));
while((text=br.readLine())!=null)
{
pw.write(text+"\n");
pw.flush();
}
//System.out.println(file);
}
else if(file.isDirectory())
{
}
}
}
public static void main(String args[])throws IOException
{
File files[] = new File("/home/gauge/Documents/Docs/Filtered Documents/Orissa/TextFiles/Year1952").listFiles();
CreateSampleDocuments d=new CreateSampleDocuments();
d.readSampleFiles(files);
}
}
'
I don't know if this is 100% percent what you need (Question is not very clear) but I think you could make your code a little bit clearer.
try {
List<Path> files = Files.list(Paths.get("path")).filter(path -> Files.isRegularFile(path)).collect(Collectors.toList());
int ten_percent = files.size()/10;
Collections.shuffle(files); //Randomize
files.stream().limit(ten_percent).forEach(source -> copyFile(source, Paths.get("newPAth").resolve(UUID.randomUUID().toString())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and the copyFile method (Just to get rid of the Exception in the forEach):
private void copyFile(Path source, Path dest) {
try {
Files.copy(source, dest);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should now copy 10% of your files into the folder.
If you need to copy complete Directories, don't use the filte in the first stream and use this method:
private void copyDirectory(final Path sourcePath, final Path targetPath) throws IOException {
Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir)));
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
Files.copy(file, targetPath.resolve(sourcePath.relativize(file)));
return FileVisitResult.CONTINUE;
}
});
}
Instead of using listfiles use list you will get both files and folder.
For all files in the String array call your readSampleFiles method. For each folder in the string array redo the same as you did in main recurssively.
I want include copyright comment on the top of every java file. I want to do it via eclipse formatter.
If it is not possible, please suggest any other way to include the copyright in existing java file.
Although it may not perfectly suit the intended approach (that is, using an eclipse plugin for that) : Once I created a small utility class that does exactly this.
It collects a list of all .java files in a given source directory. For each of the resulting files, it looks for the first line starting with the word "package". If the part above this line is not empty, then it will assume that a header is already present, and skip this file. Otherwise, it will insert a header (which is contained in some template file) before the line starting with "package".
This could arbitrarily be improved and generalized, but I only once wrote it down in order to quickly insert copyright headers into the files of an existing code base, and it worked well. Maybe you (or others) find it helpful.
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class HeaderInserter
{
public static void main(String[] args)
{
String headerTemplateFileName = "HeaderTemplate.txt";
String path = "C:/Workspace/HeaderInserter/src";
insertHeaders(path, headerTemplateFileName);
}
private static void insertHeaders(String path, String headerTemplateFileName)
{
FilenameFilter filenameFilter = new FilenameFilter()
{
#Override
public boolean accept(File dir, String name)
{
return name.toLowerCase().endsWith(".java");
}
};
List<String> headerLines = readLines(headerTemplateFileName);
List<File> files = listFiles(new File(path), filenameFilter);
for (File file : files)
{
System.out.println("Inserting header into "+file);
handle(file, headerLines);
}
System.out.println("Done");
}
private static void handle(File inputFile, List<String> headerLines)
{
List<String> lines = readLines(inputFile.getPath());
int index = lineIndexStartingWith(lines, "package");
if (index == -1)
{
System.err.println("No 'package' line found in "+inputFile);
return;
}
if (index > 0)
{
List<String> removedLines = lines.subList(0, index);
String removedPart = createString(removedLines);
String removedContents = removedPart.replaceAll("\n", "");
if (removedContents.trim().length() > 0)
{
System.err.println("Non-empty header found in "+inputFile);
System.err.println(removedPart);
System.err.println("Skipping");
return;
}
}
List<String> keptLines = lines.subList(index, lines.size());
List<String> writtenLines = new ArrayList<String>();
writtenLines.addAll(headerLines);
writtenLines.addAll(keptLines);
String writtenContent = createString(writtenLines);
File outputFile = new File(inputFile.getName()+"_header");
boolean written = writeContent(outputFile, writtenContent);
if (written)
{
boolean deleted = inputFile.delete();
if (!deleted)
{
System.err.println(
"Could not delete old input file: "+inputFile);
return;
}
boolean renamed = outputFile.renameTo(inputFile);
if (!renamed)
{
System.err.println("Could not rename "+outputFile);
System.err.println(" to "+inputFile);
return;
}
System.out.println("Inserted header into "+inputFile);
}
}
private static int lineIndexStartingWith(
List<String> lines, String prefix)
{
for (int i=0; i<lines.size(); i++)
{
String line = lines.get(i);
if (line.trim().startsWith(prefix))
{
return i;
}
}
return -1;
}
private static String createString(List<String> lines)
{
StringBuilder sb = new StringBuilder();
for (String line : lines)
{
sb.append(line).append("\n");
}
return sb.toString();
}
private static boolean writeContent(
File outputFile, String writtenContent)
{
try (FileWriter fw = new FileWriter(outputFile))
{
fw.write(writtenContent);
fw.close();
return true;
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
private static List<String> readLines(String fileName)
{
try
{
return Files.readAllLines(
Paths.get(fileName), Charset.defaultCharset());
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
private static List<File> listFiles(
File rootDirectory, FilenameFilter filenameFilter)
{
List<File> result = new ArrayList<File>();
listFiles(rootDirectory, filenameFilter, result);
return result;
}
private static void listFiles(
File file, FilenameFilter filenameFilter, List<File> result)
{
if (!file.isDirectory())
{
if (filenameFilter.accept(file.getParentFile(), file.getName()))
{
result.add(file);
}
}
else
{
File files[] = file.listFiles();
for (File f : files)
{
listFiles(f, filenameFilter, result);
}
}
}
}
Try Eclipse Releng Tools here
Write a script to update each file and add first line - use eclipse find and replace regex
http://java.dzone.com/articles/using-regular-expressions