I have an application which copies files from one directory to another. But every time I call the method to copy the files the UI (window) freezes until they´re done being copied. Do you have any idea why? It doesn't matter how many files that are in the directory as it always freezes.
This is my code:
public void startProcess(File orgDir, File destDir) {
Screen1Controller sf = new Screen1Controller();
int y = 1;
try {
File[] files = orgDir.listFiles();
for (File file : files) {
if (file.isDirectory() == false) {
File destinationPath = new File(destDir.getCanonicalPath() + "\\");
destDir = new File(destinationPath + "\\" + "");
destDir.mkdir();
System.out.println("file:" + file.getCanonicalPath());
try {
String fileNameWithOutExt = file.getName().replaceFirst("[.][^.]+$", "");
File destFile = new File(destDir.getPath() + "\\" + file.getName());
if (Files.exists(Paths.get(destFile.getPath()))) {
System.out.println("There is a duplicate.");
File[] destFiles = destDir.listFiles();
for (File destinationFile : destFiles) {
if (destinationFile.getName().startsWith(fileNameWithOutExt)) {
y++;
}
}
File newFile = new File(orgDir.getPath() + "\\" + fileNameWithOutExt + "." + y);
file.renameTo(newFile);
File destPath = new File(destDir.getPath() + "\\" + newFile.getName());
System.out.println(newFile.getCanonicalPath());
Files.copy(Paths.get(newFile.getCanonicalPath()), Paths.get(destPath.getPath()));
newFile.renameTo(new File(orgDir.getPath() + "\\" + fileNameWithOutExt));
} else {
Files.copy(Paths.get(file.getPath()), Paths.get(destFile.getPath()));
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
startProcess(file, destDir);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
You have to create a new Thread to handle the copying in a new thread and not the UI thread
new Thread(new Runnable() {
#Override
public void run() {
}
}).start();
put your method inside that, the one that is copying the files.
so it would look something like
new Thread(() -> {
startProcess(... , ...);
}).start();
Related
With this code, I can rename two Folders:
public static void main(String[] args)
{
RenameFolder f = new RenameFolder();
f.RenameFolder();
}
private void RenameFolder()
{
File f1= new File("C:\\Users\\Nm\\Desktop\\Lauer");
File f2= new File("C:\\Users\\Nm\\Desktop\\Axeler");
try {
if(f1.exists()) {
f1.renameTo(f2);
System.out.println("Folder " +f1.getName()+
" was changed into " +f2.getName() +"..." );
} else {
f1.mkdir();
System.out.println("Folder " +f1.getName()+ " was created..." );
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
How can I do that when I have to rename over thousand folders with names? For example:
raro -> noto
mano -> kaoto
Daum -> Loeme
Gato -> Rate
Ta+To -> Mo~no
etc...
put all the folder names in an array and loop through the array to rename all folders.
private void RenameFolder()
{
ArrayList CurrentName=new ArrayList();
ArrayList NewName=new ArrayList();
CurrentName.add(path);
NewName.add(path);
//repeat about two lines for as many folders you want.
for(int i=0;i<CurrentName.size()-1;i++){
File f1= new File(CurrentName.get(i));
File f2= new File(NewName.get(i));
try {
if(f1.exists()) {
f1.renameTo(f2);
System.out.println("Folder " +f1.getName()+
" was changed into " +f2.getName() +"..." );
} else {
f1.mkdir();
System.out.println("Folder " +f1.getName()+ " was created..." );
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
I am wondering if anyone can help me. I am only learning Java, what I am trying to do is read every file on c:\ and create a md5 hash of that file to compare at a later stage as well as displaying some basic counts and meta. I can't seem to recursively loop over every file and folder in the c:\ drive and I am not sure how to tackle creating an MD5 hash of each file. I am also not sure is this the best approach for so many files.
public static void main(String[] args) throws IOException {
int FileCount = 0,
DirCount = 0,
HiddenFiles = 0,
HiddenDirs = 0;
File folder = new File("/");
File[] listOfFiles = folder.listFiles();
for (File listOfFile : listOfFiles) {
Path file = listOfFile.toPath();
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
System.out.println("isOther: " + attr.isOther());
System.out.println("isRegularFile: " + attr.isRegularFile());
System.out.println("isSymbolicLink: " + attr.isSymbolicLink());
System.out.println("size: " + attr.size());
if (listOfFile.isFile()) {
System.out.println("File " + listOfFile.getName());
System.out.println("isHidden " + listOfFile.isHidden());
if (listOfFile.isHidden()) {
HiddenFiles++;
}
System.out.println("getPath " + listOfFile.getPath());
FileCount++;
} else if (listOfFile.isDirectory()) {
System.out.println("Directory " + listOfFile.getName());
System.out.println("isHidden " + listOfFile.isHidden());
System.out.println("getPath " + listOfFile.getPath());
if (listOfFile.isHidden()) {
HiddenDirs++;
}
DirCount++;
}
System.out.println("DirCount " + DirCount);
System.out.println("FileCount " + FileCount);
System.out.println("HiddenDirs " + DirCount);
System.out.println("HiddenFiles " + FileCount);
}
}
Let's create classes that will do it what do you want:
File, Folder
File is already exist, let's create class that has name XFile, not good but you will be find something better in future.
public class XFile {
private final File file;
public XFile(File file) {
this.file = file;
}
public String name() {
return file.getName();
}
//other data you want to know, create getters for all wanted information from File.
public byte[] md5() {
try (InputStream input = new BufferedInputStream(new FileInputStream(file))) {
MessageDigest md5 = MessageDigest.getInstance("MD5");
int tempByte;
while ((tempByte = input.read()) != -1) {
md5.update((byte) tempByte);
}
return md5.digest();
} catch (IOException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
and class Folder (that should be in jdk all this time)
public class Folder {
private final File underlyingDir;
private List<File> elements = null;
public Folder(File underlyingDir) {
this.underlyingDir = underlyingDir;
}
private void fetchElements() {
List<File> firstLevelElements = new ArrayList<>(Arrays.asList(underlyingDir.listFiles()));
elements = this.recursive(firstLevelElements, Integer.MAX_VALUE);
}
public List<XFile> files() {
if (elements == null) {
fetchElements();
}
return elements.stream()
.filter(File::isFile)
.map(XFile::new)
.collect(Collectors.toList());
}
public long foldersCount() {
if (elements == null) {
fetchElements();
}
return elements.stream()
.filter(File::isDirectory)
.collect(Collectors.toList())
.size();
}
public long filesCount() {
if (elements == null) {
fetchElements();
}
return elements.stream()
.filter(File::isFile)
.collect(Collectors.toList())
.size();
}
public long hiddenFiles() {
if (elements == null) {
fetchElements();
}
return elements.stream()
.filter(File::isFile)
.filter(File::isHidden)
.collect(Collectors.toList())
.size();
}
public long hiddenDirs() {
if (elements == null) {
fetchElements();
}
return elements.stream()
.filter(File::isDirectory)
.filter(File::isHidden)
.collect(Collectors.toList())
.size();
}
private List<File> recursive(List<File> elements, int depth) {
if (depth == -1) return Collections.emptyList();
List<File> result = new ArrayList<>();
for (File element : elements) {
if (element.isDirectory()) {
depth--;
result.add(element);
if (nonNull(element.listFiles())) {
result.addAll(recursive(Arrays.asList(element.listFiles()), depth));
}
} else {
result.add(element);
}
}
return result;
}
}
and test class Main
public class Main {
public static void main(String[] args) {
Folder folder = new Folder(new File("F:/"));
System.out.println("files " + folder.filesCount());
System.out.println("folders " + folder.foldersCount());
System.out.println("hidden dirs " + folder.hiddenDirs());
System.out.println("hidden files " + folder.hiddenFiles());
for (XFile file : folder.files()) {
System.out.printf("\nname: %s MD5 hash %s ", file.name(), Arrays.toString(file.md5()));
}
}
}
For some reason i can't figure out why it downloads the new applet every time even though i have the newest application on my computer already (that's what this downloader/checker does, to check the hash, and if its outdated, it re-downloads the newer version which is uploaded to web host)
My downloader class
public class Downloader {
private static final String HASH_URL = "/current";
private static final String DOWNLOAD_URL = ".jar";
private LoadingFrame loadingFrame;
public Downloader(LoadingFrame loadingFrame) {
this.loadingFrame = loadingFrame;
}
private String getLatestHash() {
loadingFrame.setLoadingText("Checking if client is up to date...");
try (InputStream in = new URL(HASH_URL).openStream()) {
return new String(IOUtils.toByteArray(in)).trim();
} catch (IOException e) {
loadingFrame.setLoadingText("Error loading client [ErrorCode: 7A]");
throw new RuntimeException("Error loading client");
}
}
public File downloadLatestPack() {
try {
File dir = new File(System.getProperty("user.home") + File.separator + "Project" + File.separator + "client");
if (!dir.exists()) {
dir.mkdirs();
}
loadingFrame.setLoadingText("Checking if client is up to date...");
String latestHash = getLatestHash();
File latest = new File(dir.getPath() + File.separator + latestHash + ".jar");
if (!latest.exists() || !com.google.common.io.Files.hash(latest, Hashing.sha1()).toString().equals(latestHash)) {
loadingFrame.setLoadingText("Doing some house keeping...");
for (File f : dir.listFiles()) {
if (f.getName().endsWith(".jar") && !f.getName().equals(latest.getName())) {
f.delete();
}
}
loadingFrame.setLoadingText("Downloading latest client...");
latest.createNewFile();
try (InputStream in = new URL(DOWNLOAD_URL).openStream()) {
Files.copy(in, latest.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} else {
loadingFrame.setLoadingText("Client is up to date!");
}
return latest;
} catch (IOException e) {
loadingFrame.setLoadingText("Error loading client [ErrorCode: 6B]");
throw new RuntimeException("Error loading client");
}
}
}
I am trying to zip multiple folders using Java. Below is my code.
if (CompressType.ZIP == zip){
File f = null;
for (File serlectFile : serlectFiles){
f = new File(serlectFile.getAbsolutePath());
filePath = f;
System.out.println("NIO Folders 1122 : " + filePath);
new Thread(new Runnable(){
public void run(){
try{
compressFolder.createZip(filePath.getPath(), destination.getPath());
JOptionPane.showMessageDialog(null, " Backup Created .....", "Alert", 1);
dispose();
} catch (IOException ex){
JOptionPane.showMessageDialog(null, "Error ! ");
ex.printStackTrace();
}
}
}).start();
}
}
This is the code I've tried to do above task . But unfortunately I couldn't complete it . Because when I send 'filepath.getPath()' to 'createZip()' method it is got just only one directory at the time . But when I was printed filepath before the method calling it gave me following . ''NIO Folders 1122 : C:\Users\user\Desktop\backup ''-
'' NIO Folders 1122 : C:\Users\user\Desktop\contact''.
The reason I can think is, the applicartion is running without waiting for one thread to complete. Therefore all the threads are running in a loop. Below is my zipping code, which runs inside the above mentioned thread.
public void createZip(String directoryPath, String zipPath) throws IOException{
value = countFilesInDirectory(new File(directoryPath));
ExpressWizard.backupProgressBar.setMaximum(value);
FileOutputStream fOut = null;
BufferedOutputStream bOut = null;
ZipArchiveOutputStream tOut = null;
try{
fOut = new FileOutputStream(new File(zipPath));
bOut = new BufferedOutputStream(fOut);
tOut = new ZipArchiveOutputStream(bOut);
addFileToZip(tOut, directoryPath, "");
} finally {
tOut.finish();
tOut.close();
bOut.close();
fOut.close();
}
}
#SuppressWarnings("empty-statement")
private void addFileToZip(ZipArchiveOutputStream zOut, String path, String base) throws IOException{
File f = new File(path);
String entryName = base + f.getName();
ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName);
zOut.putArchiveEntry(zipEntry);
if (f.isFile()) {
FileInputStream fInputStream = null;
try{
fInputStream = new FileInputStream(f);
IOUtils.copy(fInputStream, zOut);
zOut.closeArchiveEntry();
} finally {
IOUtils.closeQuietly(fInputStream);
}
System.out.println(f.getAbsolutePath());
counter++;
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
ExpressWizard.backupProgressBar.setValue(counter);
ExpressWizard.filesTextArea.append(f.getAbsolutePath() + "\n");
}
});
if (ExpressWizard.backupProgressBar.getValue() == counter){
ExpressWizard.backUpButton.setEnabled(false);
}
} else{
zOut.closeArchiveEntry();
File[] children = f.listFiles();
if (children != null){
for (File child : children){
addFileToZip(zOut, child.getAbsolutePath(), entryName + "/");
System.out.println("File: " + child.getAbsolutePath());
}
}
}
}
How can I execute this code, one by one? In other words, the zip file thread should run for one folder; the loop should wait; when the zip is completes, the second folder starts zipping; The loop waits for the end of thread; then the third folder and so on.
Any ideas?
I'm taking HTML file and one XSLT file as input and generating HTML output but in my folder there are multiple HTML files and I've to take each of them as input and generate the corresponding output file while XSLT input file remains same every time. Currently in my code I'm repeating the code block every time to take the input HTML file. Instead of this I want to iterate over all the HTML files in the folder and take them as input file one by one to generate the output. In my current code file names are also fixed like part_1.html but it can vary and in that case this code won't work and this will create problem. Can anyone please help out in this matter:
Thanking you!
Current Java code (Sample for two files):
public void tranformation() {
// TODO Auto-generated method stub
transform1();
transform2();
}
public static void transform1(){
String inXML = "C:/SCORM_CP/part_1.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part1_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_1.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public static void transform2(){
String inXML = "C:/SCORM_CP/part_2.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part2_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_2.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public void transform(String inXML,String inXSL,String outTXT)
throws TransformerConfigurationException,
TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inXSL);
Transformer transformer = factory.newTransformer(xslStream);
transformer.setErrorListener(new MyErrorListener());
StreamSource in = new StreamSource(inXML);
StreamResult out = new StreamResult(outTXT);
transformer.transform(in,out);
System.out.println("The generated XML file is:" + outTXT);
}
}
File dir = new File("/path/to/dir");
File[] htmlFiles = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".html");
}
});
if (htmlFiles != null) for (File html: htmlFiles) {
...
}
You have to implement something like
public class Transformation {
public static void main (String[] args){
transformation(".", ".");
}
public static void transform(String inXML, String inXSL, String outTXT, String renamedFile){
System.out.println(inXML);
System.out.println(inXSL);
System.out.println(outTXT);
System.out.println(renamedFile);
}
public static void transformation(String inFolder, String outFolder){
File infolder = new File(inFolder);
File outfolder = new File(outFolder);
if (infolder.isDirectory() && outfolder.isDirectory()){
System.out.println("In " + infolder.getAbsolutePath());
System.out.println("Out " + outfolder.getAbsolutePath());
File[] listOfFiles = infolder.listFiles();
String outPath = outfolder.getAbsolutePath();
String inPath = infolder.getAbsolutePath();
for (File f: listOfFiles) {
if (f.isFile() ) {
System.out.println("File " + f.getName());
int indDot = f.getName().lastIndexOf(".");
String name = f.getName().substring(0, indDot);
String ext = f.getName().substring(indDot+1);
if (ext != null && ext.equals("html")){
transform(f.getAbsolutePath(), inPath+File.separator+name+".xsl", outPath+File.separator+name+".txt", outPath+File.separator+name+".html");
}
}
}
}
}
}
First you should write a method that take inXML, inXSL, outTXT and renamedFile as arguments.
Then, using the list() method of the File class, that eventually take a FilenameFilter, you may iterate over the files you want to transform.
Here is a sample of FilenameFilter :
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.contains("part");
}
};
Regards
use DirectoryScanner which will make your job easier
Example of usage:
String[] includes = {"**\*.html"};
ds.setIncludes(includes);
ds.setBasedir(new File("test"));
ds.setCaseSensitive(true);
ds.scan();
System.out.println("FILES:");
String[] files = ds.getIncludedFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/DirectoryScanner.html