Instead of renaming my file just duplicating - java

I have a program that should process the files in the directory and if the file size is more than 50 bytes delete it. Otherwise, if the file size is less then 50 bytes program should rename the args[1] file to the allFilesContent.txt(same directory), and write all the files to this file, separated by "n" (110 ASCII code). But instead the program just creates another file and writes to the very first args[1] file. What's the problem?
public class Solution
{
public static void main(String [] args) throws IOException
{
File path = new File(args[0]);
File resultFileAbsolutePath = new File(args[1]);
ArrayList<File> allFiles = new ArrayList<>();
boolean isRenamed = false;
for(File file : path.listFiles())
{
if(file.length() > 50)
{
FileUtils.deleteFile(file);
}
else if(file.length() <= 50)
{
if(!isRenamed)
{
FileUtils.renameFile(resultFileAbsolutePath, new File(resultFileAbsolutePath.getParent()+"\\allFilesContent.txt"));
isRenamed = true;
}
if(!file.getName().equals(resultFileAbsolutePath.getName()))
{
allFiles.add(file);
}
}
}
Collections.sort(allFiles, new Comparator<File>()
{
#Override
public int compare(File o1, File o2)
{
return o1.getName().compareTo(o2.getName());
}
});
FileOutputStream fileOutputStream = new FileOutputStream(resultFileAbsolutePath, true);
for (File file : allFiles)
{
try(FileInputStream fileInputStream = new FileInputStream(file))
{
if(allFiles.indexOf(file) != 0) fileOutputStream.write(110);
int data;
while(fileInputStream.available() > 0)
{
data = fileInputStream.read();
fileOutputStream.write(data);
}
}
}
fileOutputStream.close();
}
public static void deleteFile(File file)
{
if (!file.delete())
{
System.out.println("Can not delete file with name " + file.getName());
}
}
}
And FileUtils class
import java.io.File;
public class FileUtils
{
public static void deleteFile(File file)
{
if (!file.delete())
{
System.out.println("Can not delete file with name " + file.getName());
}
}
public static void renameFile(File source, File destination)
{
if (!source.renameTo(destination))
{
System.out.println("Can not rename file with name " + source.getName());
}
}
}

You have following statement: "FileOutputStream fileOutputStream = new FileOutputStream(resultFileAbsolutePath, true);"
Instead of "true" put "false". It should work.

Related

How to get dynamic name of .zip file after download in JAVA [duplicate]

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
How to read all the files in a folder through Java? It doesn't matter which API.
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);
Files.walk API is available from Java 8.
try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
paths
.filter(Files::isRegularFile)
.forEach(System.out::println);
}
The example uses try-with-resources pattern recommended in API guide. It ensures that no matter circumstances the stream will be closed.
File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
}
}
In Java 8 you can do this
Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
which will print all files in a folder while excluding all directories. If you need a list, the following will do:
Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.collect(Collectors.toList())
If you want to return List<File> instead of List<Path> just map it:
List<File> filesInFolder = Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.map(Path::toFile)
.collect(Collectors.toList());
You also need to make sure to close the stream! Otherwise you might run into an exception telling you that too many files are open. Read here for more information.
All of the answers on this topic that make use of the new Java 8 functions are neglecting to close the stream. The example in the accepted answer should be:
try (Stream<Path> filePathStream=Files.walk(Paths.get("/home/you/Desktop"))) {
filePathStream.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
}
From the javadoc of the Files.walk method:
The returned stream encapsulates one or more DirectoryStreams. If
timely disposal of file system resources is required, the
try-with-resources construct should be used to ensure that the
stream's close method is invoked after the stream operations are completed.
One remark according to get all files in the directory.
The method Files.walk(path) will return all files by walking the file tree rooted at the given started file.
For instance, there is the next file tree:
\---folder
| file1.txt
| file2.txt
|
\---subfolder
file3.txt
file4.txt
Using the java.nio.file.Files.walk(Path):
Files.walk(Paths.get("folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
Gives the following result:
folder\file1.txt
folder\file2.txt
folder\subfolder\file3.txt
folder\subfolder\file4.txt
To get all files only in the current directory use the java.nio.file.Files.list(Path):
Files.list(Paths.get("folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
Result:
folder\file1.txt
folder\file2.txt
import java.io.File;
public class ReadFilesFromFolder {
public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
static String temp = "";
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
listFilesForFolder(folder);
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
// System.out.println("Reading files under the folder "+folder.getAbsolutePath());
listFilesForFolder(fileEntry);
} else {
if (fileEntry.isFile()) {
temp = fileEntry.getName();
if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt"))
System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
}
}
}
}
}
In Java 7 and higher you can use listdir
Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file: stream) {
System.out.println(file.getFileName());
}
} catch (IOException | DirectoryIteratorException x) {
// IOException can never be thrown by the iteration.
// In this snippet, it can only be thrown by newDirectoryStream.
System.err.println(x);
}
You can also create a filter that can then be passed into the newDirectoryStream method above
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
public boolean accept(Path file) throws IOException {
try {
return (Files.isRegularFile(path));
} catch (IOException x) {
// Failed to determine if it's a file.
System.err.println(x);
return false;
}
}
};
For other filtering examples, [see documentation].(http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob)
private static final String ROOT_FILE_PATH="/";
File f=new File(ROOT_FILE_PATH);
File[] allSubFiles=f.listFiles();
for (File file : allSubFiles) {
if(file.isDirectory())
{
System.out.println(file.getAbsolutePath()+" is directory");
//Steps for directory
}
else
{
System.out.println(file.getAbsolutePath()+" is file");
//steps for files
}
}
Just walk through all Files using Files.walkFileTree (Java 7)
Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("file: " + file);
return FileVisitResult.CONTINUE;
}
});
If you want more options, you can use this function which aims to populate an arraylist of files present in a folder. Options are : recursivility and pattern to match.
public static ArrayList<File> listFilesForFolder(final File folder,
final boolean recursivity,
final String patternFileFilter) {
// Inputs
boolean filteredFile = false;
// Ouput
final ArrayList<File> output = new ArrayList<File> ();
// Foreach elements
for (final File fileEntry : folder.listFiles()) {
// If this element is a directory, do it recursivly
if (fileEntry.isDirectory()) {
if (recursivity) {
output.addAll(listFilesForFolder(fileEntry, recursivity, patternFileFilter));
}
}
else {
// If there is no pattern, the file is correct
if (patternFileFilter.length() == 0) {
filteredFile = true;
}
// Otherwise we need to filter by pattern
else {
filteredFile = Pattern.matches(patternFileFilter, fileEntry.getName());
}
// If the file has a name which match with the pattern, then add it to the list
if (filteredFile) {
output.add(fileEntry);
}
}
}
return output;
}
Best, Adrien
File directory = new File("/user/folder");
File[] myarray;
myarray=new File[10];
myarray=directory.listFiles();
for (int j = 0; j < myarray.length; j++)
{
File path=myarray[j];
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String s = "";
while (br.ready()) {
s += br.readLine() + "\n";
}
}
nice usage of java.io.FileFilter as seen on https://stackoverflow.com/a/286001/146745
File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
static File mainFolder = new File("Folder");
public static void main(String[] args) {
lf.getFiles(lf.mainFolder);
}
public void getFiles(File f) {
File files[];
if (f.isFile()) {
String name=f.getName();
} else {
files = f.listFiles();
for (int i = 0; i < files.length; i++) {
getFiles(files[i]);
}
}
}
I think this is good way to read all the files in a folder and sub folder's
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
files.add(path.get(i));
}
}
}
if(input.isFile())
{
files.add(input);
}
}
Simple example that works with Java 1.7 to recursively list files in directories specified on the command-line:
import java.io.File;
public class List {
public static void main(String[] args) {
for (String f : args) {
listDir(f);
}
}
private static void listDir(String dir) {
File f = new File(dir);
File[] list = f.listFiles();
if (list == null) {
return;
}
for (File entry : list) {
System.out.println(entry.getName());
if (entry.isDirectory()) {
listDir(entry.getAbsolutePath());
}
}
}
}
While I do agree with Rich, Orian and the rest for using:
final File keysFileFolder = new File(<path>);
File[] fileslist = keysFileFolder.listFiles();
if(fileslist != null)
{
//Do your thing here...
}
for some reason all the examples here uses absolute path (i.e. all the way from root, or, say, drive letter (C:\) for windows..)
I'd like to add that it is possible to use relative path as-well.
So, if you're pwd (current directory/folder) is folder1 and you want to parse folder1/subfolder, you simply write (in the code above instead of ):
final File keysFileFolder = new File("subfolder");
Java 8 Files.walk(..) is good when you are soore it will not throw Avoid Java 8 Files.walk(..) termination cause of ( java.nio.file.AccessDeniedException ) .
Here is a safe solution , not though so elegant as Java 8Files.walk(..) :
int[] count = {0};
try {
Files.walkFileTree(Paths.get(dir.getPath()), new HashSet<FileVisitOption>(Arrays.asList(FileVisitOption.FOLLOW_LINKS)),
Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file , BasicFileAttributes attrs) throws IOException {
System.out.printf("Visiting file %s\n", file);
++count[0];
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file , IOException e) throws IOException {
System.err.printf("Visiting failed for %s\n", file);
return FileVisitResult.SKIP_SUBTREE;
}
#Override
public FileVisitResult preVisitDirectory(Path dir , BasicFileAttributes attrs) throws IOException {
System.out.printf("About to visit directory %s\n", dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
void getFiles(){
String dirPath = "E:/folder_name";
File dir = new File(dirPath);
String[] files = dir.list();
if (files.length == 0) {
System.out.println("The directory is empty");
} else {
for (String aFile : files) {
System.out.println(aFile);
}
}
}
package com;
import java.io.File;
/**
*
* #author ?Mukesh
*/
public class ListFiles {
static File mainFolder = new File("D:\\Movies");
public static void main(String[] args)
{
ListFiles lf = new ListFiles();
lf.getFiles(lf.mainFolder);
long fileSize = mainFolder.length();
System.out.println("mainFolder size in bytes is: " + fileSize);
System.out.println("File size in KB is : " + (double)fileSize/1024);
System.out.println("File size in MB is :" + (double)fileSize/(1024*1024));
}
public void getFiles(File f){
File files[];
if(f.isFile())
System.out.println(f.getAbsolutePath());
else{
files = f.listFiles();
for (int i = 0; i < files.length; i++) {
getFiles(files[i]);
}
}
}
}
Just to expand on the accepted answer I store the filenames to an ArrayList (instead of just dumping them to System.out.println) I created a helper class "MyFileUtils" so it could be imported by other projects:
class MyFileUtils {
public static void loadFilesForFolder(final File folder, List<String> fileList){
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
loadFilesForFolder(fileEntry, fileList);
} else {
fileList.add( fileEntry.getParent() + File.separator + fileEntry.getName() );
}
}
}
}
I added the full path to the file name.
You would use it like this:
import MyFileUtils;
List<String> fileList = new ArrayList<String>();
final File folder = new File("/home/you/Desktop");
MyFileUtils.loadFilesForFolder(folder, fileList);
// Dump file list values
for (String fileName : fileList){
System.out.println(fileName);
}
The ArrayList is passed by "value", but the value is used to point to the same ArrayList object living in the JVM Heap. In this way, each recursion call adds filenames to the same ArrayList (we are NOT creating a new ArrayList on each recursive call).
There are many good answers above, here's a different approach: In a maven project, everything you put in the resources folder is copied by default in the target/classes folder. To see what is available at runtime
ClassLoader contextClassLoader =
Thread.currentThread().getContextClassLoader();
URL resource = contextClassLoader.getResource("");
File file = new File(resource.toURI());
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f.getName());
}
Now to get the files from a specific folder, let's say you have a folder called 'res' in your resources folder, just replace:
URL resource = contextClassLoader.getResource("res");
If you want to have access in your com.companyName package then:
contextClassLoader.getResource("com.companyName");
You can put the file path to argument and create a list with all the filepaths and not put it the list manually. Then use a for loop and a reader. Example for txt files:
public static void main(String[] args) throws IOException{
File[] files = new File(args[0].replace("\\", "\\\\")).listFiles(new FilenameFilter() { #Override public boolean accept(File dir, String name) { return name.endsWith(".txt"); } });
ArrayList<String> filedir = new ArrayList<String>();
String FILE_TEST = null;
for (i=0; i<files.length; i++){
filedir.add(files[i].toString());
CSV_FILE_TEST=filedir.get(i)
try(Reader testreader = Files.newBufferedReader(Paths.get(FILE_TEST));
){
//write your stuff
}}}
package com.commandline.folder;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FolderReadingDemo {
public static void main(String[] args) {
String str = args[0];
final File folder = new File(str);
// listFilesForFolder(folder);
listFilesForFolder(str);
}
public static void listFilesForFolder(String str) {
try (Stream<Path> paths = Files.walk(Paths.get(str))) {
paths.filter(Files::isRegularFile).forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
We can use org.apache.commons.io.FileUtils, use listFiles() mehtod to read all the files in a given folder.
eg:
FileUtils.listFiles(directory, new String[] {"ext1", "ext2"}, true)
This read all the files in the given directory with given extensions, we can pass multiple extensions in the array and read recursively within the folder(true parameter).
public static List<File> files(String dirname) {
if (dirname == null) {
return Collections.emptyList();
}
File dir = new File(dirname);
if (!dir.exists()) {
return Collections.emptyList();
}
if (!dir.isDirectory()) {
return Collections.singletonList(file(dirname));
}
return Arrays.stream(Objects.requireNonNull(dir.listFiles()))
.collect(Collectors.toList());
}
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AvoidNullExp {
public static void main(String[] args) {
List<File> fileList =new ArrayList<>();
final File folder = new File("g:/master");
new AvoidNullExp().listFilesForFolder(folder, fileList);
}
public void listFilesForFolder(final File folder,List<File> fileList) {
File[] filesInFolder = folder.listFiles();
if (filesInFolder != null) {
for (final File fileEntry : filesInFolder) {
if (fileEntry.isDirectory()) {
System.out.println("DIR : "+fileEntry.getName());
listFilesForFolder(fileEntry,fileList);
} else {
System.out.println("FILE : "+fileEntry.getName());
fileList.add(fileEntry);
}
}
}
}
}
list down files from Test folder present inside class path
import java.io.File;
import java.io.IOException;
public class Hello {
public static void main(final String[] args) throws IOException {
System.out.println("List down all the files present on the server directory");
File file1 = new File("/prog/FileTest/src/Test");
File[] files = file1.listFiles();
if (null != files) {
for (int fileIntList = 0; fileIntList < files.length; fileIntList++) {
String ss = files[fileIntList].toString();
if (null != ss && ss.length() > 0) {
System.out.println("File: " + (fileIntList + 1) + " :" + ss.substring(ss.lastIndexOf("\\") + 1, ss.length()));
}
}
}
}
}
/**
* Function to read all mp3 files from sdcard and store the details in an
* ArrayList
*/
public ArrayList<HashMap<String, String>> getPlayList()
{
ArrayList<HashMap<String, String>> songsList=new ArrayList<>();
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put(
"songTitle",
file.getName().substring(0,
(file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which have a .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter
{
#Override
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
You can filter any textfiles or any other extension ..just replace it with .MP3
This will Read Specified file extension files in given path(looks sub folders also)
public static Map<String,List<File>> getFileNames(String
dirName,Map<String,List<File>> filesContainer,final String fileExt){
String dirPath = dirName;
List<File>files = new ArrayList<>();
Map<String,List<File>> completeFiles = filesContainer;
if(completeFiles == null) {
completeFiles = new HashMap<>();
}
File file = new File(dirName);
FileFilter fileFilter = new FileFilter() {
#Override
public boolean accept(File file) {
boolean acceptFile = false;
if(file.isDirectory()) {
acceptFile = true;
}else if (file.getName().toLowerCase().endsWith(fileExt))
{
acceptFile = true;
}
return acceptFile;
}
};
for(File dirfile : file.listFiles(fileFilter)) {
if(dirfile.isFile() &&
dirfile.getName().toLowerCase().endsWith(fileExt)) {
files.add(dirfile);
}else if(dirfile.isDirectory()) {
if(!files.isEmpty()) {
completeFiles.put(dirPath, files);
}
getFileNames(dirfile.getAbsolutePath(),completeFiles,fileExt);
}
}
if(!files.isEmpty()) {
completeFiles.put(dirPath, files);
}
return completeFiles;
}
This will work fine:
private static void addfiles(File inputValVal, ArrayList<File> files)
{
if(inputVal.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(inputVal.listFiles()));
for(int i=0; i<path.size(); ++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
files.add(path.get(i));
}
}
/* Optional : if you need to have the counts of all the folders and files you can create 2 global arrays
and store the results of the above 2 if loops inside these arrays */
}
if(inputVal.isFile())
{
files.add(inputVal);
}
}

Recursive method for reading files not working

I have this method here, I want to look in a folder recursively to count files that startsWith "D".
It is showing me the StackOverflowError.
public void CountThem() throws FileNotFoundException, IOException{
int count = 0;
File []files = file.listFiles();
for(File f : files){
if(f.isDirectory()){
CountThem();
}else{
if(f.getName().startsWith("D")){
count++;
}
}
}
}
It's because when a File is a directory, you're starting over your function, that makes an infinite loop. You would have to define the function, that takes a File as a parameter:
public int countThem(File file) throws FileNotFoundException, IOException{
int count = 0;
File []files = file.listFiles();
for(File f : files){
if(f.isDirectory()) {
count += countThem(f);
} else {
if(f.getName().startsWith("D")) {
count++;
}
}
}
return count;
}
P.S.: In java it's a standard to start method names lowercase.
Edit:
public class Fajlla {
File folder;
FileReader fr;
BufferedReader br;
PrintWriter pw;
public Fajlla(String fld)throws IOException{
folder = new File(fld);
if(!folder.isDirectory()){
throw new IOException("Nuk eshte folder");
}
pw = new PrintWriter(new File("C:/Users/Admin/Desktop/dreniii.txt"));
}
public int callItOUU() throws IOException{
return this.countThem(folder);
}
public int countThem(File folder){
int count = 0;
File [] files = folder.listFiles();
for (File file : files) {
if(file.isDirectory()){
count+=countThem(file);
}if(file.isFile() && file.canRead()){
count++;
}
}
return count;
}
public static void main(String[] args) {
try {
Fajlla f = new Fajlla("C:/Users/Admin/Desktop/New folder");
int count = f.callItOUU(new File("C:/Users/Admin/Desktop/dreniii.txt"));
System.out.println(count);
} catch (IOException ex) {
Logger.getLogger(Fajlla.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is the full code
public class Fajlla {
File folder;
FileReader fr;
BufferedReader br;
PrintWriter pw;
public Fajlla(String fld)throws IOException{
folder = new File(fld);
if(!folder.isDirectory()){
throw new IOException("Nuk eshte folder");
}
pw = new PrintWriter(new File("C:/Users/Admin/Desktop/dreniii.txt"));
}
public int callItOUU() throws IOException{
return this.countThem(folder);
}
public int countThem(File folder){
int count = 0;
File [] files = folder.listFiles();
for (File file : files) {
if(file.isDirectory()){
count+=countThem(folder);
}if(file.isFile() && file.canRead()){
count++;
}
}
return count;
}
public static void main(String[] args) {
try {
Fajlla f = new Fajlla("C:/Users/Admin/Desktop/New folder");
int count = f.callItOUU();
System.out.println(count);
} catch (IOException ex) {
Logger.getLogger(Fajlla.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

How to Convert List of Folders and SubFolder into JSOn FOrmat

i want to populate Folder Name With Sub Folder name on KendoDrop Down . so i want to Convert Folder Directory in JSOn Format How can i Do That ?
public class FolderPath {
public static void main(String[] args) throws IOException {
File currentDir = new File("Folder URL "); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
StringBuilder sb1 = new StringBuilder("[");
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
sb1 = sb1.append("{\"JSONKEY\":\"" + file.getCanonicalPath() + "\"},");
String str = file.getCanonicalPath();
displayDirectoryContents(file);
} else {
}
}
sb1.deleteCharAt(sb1.length() - 1);
sb1 = sb1.append("]");
System.out.println("s2==>" + sb1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here i am Not Getting Full Directroy into JSOn Please Help
You are creating a StringBuilder object on each iteration. That's why your concatenation does not work.
Consider the contents of you C:\test is composed of 3 directories:
c:\test
|
+--css
| +--less
+--js
The code below, returns:
[{"JSONKEY":"C:\test\css"},
{"JSONKEY":"C:\test\css\less"},
{"JSONKEY":"C:\test\js"}]
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class FolderPath {
private static FileFilter onlyDirectories = new FileFilter() {
#Override
public boolean accept(File file) {
return file.isDirectory();
}
};
public static void main(String[] args) {
File currentDir = new File("C:\\test"); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
StringBuilder sb1 = new StringBuilder("[");
doDisplayDirectoryContents(dir, sb1);
if (sb1.length() > 1) {
sb1.deleteCharAt(sb1.length() - 1);
}
sb1.append("]");
System.out.println(sb1);
}
private static void doDisplayDirectoryContents(File dir, StringBuilder sb1) {
File[] files = dir.listFiles(onlyDirectories);
if (files != null) {
for (File file : files) {
try {
sb1.append("{\"JSONKEY\":\"" + file.getCanonicalPath() + "\"},");
doDisplayDirectoryContents(file, sb1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public List<Object> getDirectoryContents(String path) throws IOException {
File directory = new File(path);
File[] files;
enter code here FileFilter fileFilter = file -> file.isDirectory() || file.isFile();
files = directory.listFiles(fileFilter);
List<Object> directoryContent = new ArrayList<>();
if(files != null) {
for (int i = 0; i < files.length; i++) {
File filename = files[i];
String folderPath[] =filename.toString().split("/");
if(files[i].isDirectory()) {
Folder folder = new Folder();
folder.setName(folderPath[folderPath.length - 1]);
folder.setType("folder");
folder.setChildren(mapper.readTree(mapper.writeValueAsString(getDirectoryContents(path + "/" + folder.getName()))));
directoryContent.add(folder);
}
else{
Files file = new Files();
file.setName(folderPath[folderPath.length - 1]);
file.setType("file");
directoryContent.add(file);
}
}
}
return directoryContent;
}
public class Files {
private String name;
private String type = "file";
}
public class Folder {
private String name;
private String type = "folder";
private JsonNode children;
}

Copying children files of a source to a destination in Java

I'm trying to make a program that copies a directory's children, and I can't label all the specific names because they vary throughout each folder. Here's the code I have, but if the source is "C:\src" and the output is "C:\dst" it'll create the folder "C:\dst\src(children files)", but I want to make "C:\dst(children files)". Can anyone help?
public static void copy(File source, File destination) throws IOException {
if (source == null) {
throw new NullPointerException("Null Source");
}
if (destination == null) {
throw new NullPointerException("Null Destination");
}
if (source.isDirectory()) {
copyDirectory(source, destination);
} else {
copyFile(source, destination);
}
}
//converts to location
public static void copyDirectory(File source, File destination) throws IOException {
copyDirectory(source, destination, null);
}
public static void copyDirectory(File source, File destination, FileFilter filter) throws IOException {
File nextDirectory = new File(destination, source.getName());
if (!nextDirectory.exists() && !nextDirectory.mkdirs()) {// create the directory if necessary...
Object[] filler = {nextDirectory.getAbsolutePath()};
String message = "Dir Copy Failed";
throw new IOException(message);
}
File[] files = source.listFiles();
for (int n = 0; n < files.length; ++n) {// and then all the items below the directory...
if (filter == null || filter.accept(files[n])) {
if (files[n].isDirectory()) {
copyDirectory(files[n], nextDirectory, filter);
} else {
copyFile(files[n], nextDirectory);
}
}
}
}
public static void copyFile(File source, File destination) throws IOException {
// what we really want to do is create a file with the same name in that dir
if (destination.isDirectory()) {
destination = new File(destination, source.getName());
}
FileInputStream input = new FileInputStream(source);
copyFile(input, destination);
}
public static void copyFile(InputStream input, File destination) throws IOException {
OutputStream output = null;
try {
output = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int bytesRead = input.read(buffer);
while (bytesRead >= 0) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
} catch (Exception e) {
//
} finally {
input.close();
output.close();
}
input = null;
output = null;
}
Replace
if (source.isDirectory()) {
copyDirectory(source, destination);
} else {
copyFile(source, destination);
}
By
if (source.isDirectory()) {
for (File child : source.listFiles()) {
if (child.isDirectory()) {
copyDirectory(child, destination);
} else {
copyFile(child, destination);
}
}
} else {
copyFile(source, destination);
}
use getParentFile() to get the parent directory:
if (source.isDirectory()) {
copyDirectory(source, destination.getParentFile());
} else {
copyFile(source, destination.getParentFile());
}
You can do everything here in one line using commons-io library :
FileUtils.copyDirectory(src, dest);
see :
http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#copyDirectory%28java.io.File,%20java.io.File%29
jar file : http://mvnrepository.com/artifact/commons-io/commons-io/2.4
Try this one. copying whole files in a folder from source to destination.
import java.io.*;
public class copydir
{
public static void main(String args[])
{
File srcFolder = new File("E://Paresh/programs/test");
File destFolder = new File("D://paresh");
if(!srcFolder.exists())
{
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}
else{
try{
copyDirectory(srcFolder,destFolder);
}
catch(IOException e)
{
e.printStackTrace();
//error, just exit
System.exit(0);
}
}
System.out.println("Done");
}
public static void copyDirectory(File src , File target) throws IOException
{
if (src.isDirectory())
{
if (!target.exists())
{
target.mkdir();
}
String[] children = src.list();
for (int i=0; i<children.length; i++)
{
copyDirectory(new File(src, children[i]),new File(target, children[i]));
}
}
// if Directory exists then only files copy
else
{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(target);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}

JTextArea appending problems

Im making a backup program, and I want everything that i have the program backing up displayed on a JTextArea. well, it works, but only after the program is finished with the backup. How do i fix this? The code i have running this is here:
backup method
public void startBackup() throws Exception {
// txtarea is the JTextArea
Panel.txtArea.append("Starting Backup...\n");
for (int i = 0; i < al.size(); i++) {
//al is an ArrayList that holds all of the backup assignments selected
// from the JFileChooser
File file = new File((String) al.get(i));
File directory = new File(dir);
CopyFolder.copyFolder(file, directory);
}
}
Copy Folder class:
public class CopyFolder {
public static void copyFolder(File src, File dest) throws IOException {
if (src.isDirectory()) {
// if directory not exists, create it
if (!dest.exists()) {
dest.mkdir();
Panel.txtArea.append("Folder " + src.getName()
+ " was created\n");
}
// list all the directory contents
String files[] = src.list();
for (String file : files) {
// construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
// recursive copy
copyFolder(srcFile, destFile);
}
} else {
try {
CopyFile.copyFile(src, dest);
} catch (Exception e) {
}
}
}
}
CopyFile class
public class CopyFile {
public static void copyFile(File src, File dest) throws Exception {
// if file, then copy it
// Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
// System.out.println("File copied from " + src + " to " + dest);
Panel.txtArea.append("File copied " + src.getName() + "\n");
}
}
Thanks for the help in advance, and let me know of any assistance i can give. I did a google search on this, and it does seem to be a big problem, but i just cant think of how to fix it. Oh, and please dont downvote this just because it doesnt apply to you, its very aggravating. Thanks in advance again!
EDIT:
This is what i got:
public class test extends SwingWorker<Void, String> {
String txt;
JTextArea txtArea = null;
public test(JTextArea txtArea, String str) {
txt = str;
this.txtArea = txtArea;
}
protected Void doInBackground() throws Exception {
return null;
}
protected void process(String str) {
txtArea.append(str);
}
protected void getString() {
publish(txt);
}
}
The main problem you're having is you're trying to perform blocking actions in the Event Dispatching Thread. This will prevent the UI from been updated as repaint requests are not reaching the repaint manager until AFTER you've finished.
To over come this, you're going to need to off load the blocking work (ie the back up process) to a separate thread.
For this I suggest you have a read through the Concurrency in Swing Trail which will provide you with some useful strategies to solve your particular problem. In particular, you'll probably benifit from using a SwingWorker
Take a close look at doInBackground and the process methods
UPDATED with Example
Okay, so this is a REALLY simple example. This basically walks you C:\ drive to 3 directories deep and dumps the content to the supplied JTextArea
public class BackgroundWorker extends SwingWorker<Object, File> {
private JTextArea textArea;
public BackgroundWorker(JTextArea textArea) {
this.textArea = textArea;
}
#Override
protected Object doInBackground() throws Exception {
list(new File("C:\\"), 0);
return null;
}
#Override
protected void process(List<File> chunks) {
for (File file : chunks) {
textArea.append(file.getPath() + "\n");
}
textArea.setCaretPosition(textArea.getText().length() - 1);
}
protected void list(File path, int level) {
if (level < 4) {
System.out.println(level + " - Listing " + path);
File[] files = path.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
publish(path);
for (File file : files) {
System.out.println(file);
publish(file);
}
files = path.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory() && !pathname.isHidden();
}
});
for (File folder : files) {
list(folder, level + 1);
}
}
}
}
You would simply call new BackgroundWorker(textField).execute() and walk away :D
UPDATED with explicit example
public class BackgroundWorker extends SwingWorker<Object, String> {
private JTextArea textArea;
private File sourceDir;
private File destDir;
public BackgroundWorker(JTextArea textArea, File sourceDir, File destDir) {
this.textArea = textArea;
this.sourceDir = sourceDir;
this.destDir = destDirl
}
#Override
protected Object doInBackground() throws Exception {
if (sourceDir.isDirectory()) {
// if directory not exists, create it
if (!destDir.exists()) {
destDir.mkdir();
publish("Folder " + sourceDir.getName() + " was created");
}
// list all the directory contents
String files[] = sourceDir.list();
for (String file : files) {
// construct the src and dest file structure
File srcFile = new File(sourceDir, file);
File destFile = new File(destDir, file);
// recursive copy
copyFolder(srcFile, destFile);
}
} else {
try {
copyFile(sourceDir, destDir);
} catch (Exception e) {
}
}
return null;
}
public void copyFolder(File src, File dest) throws IOException {
if (src.isDirectory()) {
// if directory not exists, create it
if (!dest.exists()) {
publish("Folder " + src.getName() + " was created");
}
// list all the directory contents
String files[] = src.list();
for (String file : files) {
// construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
// recursive copy
copyFolder(srcFile, destFile);
}
} else {
try {
copyFile(src, dest);
} catch (Exception e) {
}
}
}
public void copyFile(File src, File dest) throws Exception {
// if file, then copy it
// Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
publish("File copied " + src.getName());
}
#Override
protected void process(List<String> chunks) {
for (String msg : chunks) {
textArea.append(msg + "\n");
}
textArea.setCaretPosition(textArea.getText().length() - 1);
}
}
Now to run...
new BackgroundWorker(textArea, sourceDir, destDir).execute();

Categories

Resources