This is my java file :
import java.io.File;
import java.lang.String;
public class ListFiles {
public static void main(String[] args) {
// Directory path here
String path = "D:/xmlfiles/";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
System.out.println(files);
}
}
}
}
This is my JS file :
function display(){
el = document.getElementById("text");
el.addEventListener("oncommand", display, true);
//loading Encryption Class
//alert('hffffi');
var myClass = cl.loadClass('ListFiles'); // use the same loader from above
var myObj = myClass.newInstance();
// Pass whatever arguments you need (they'll be auto-converted to Java form, taking into account the LiveConnect conversion rules)
var Files = myObj.String;
alert('karthik it works'+Files);
document.getElementById("text").value=Files;
}
Explanation :
I'm trying to get the ouptput string of java into my JS. I'm able to connect JAVA with JS using Live connect in XUL Firefox.
The problem right now, how can display the output of java in my JS file.
Thanks guys.
If I understand you correctly, var Files = myObj.String; is supposed to return the output of the Java program?!
I dunno that much about LiveConnect, but I'd more expect the ListFiles class to have a method that returns the list. Currently it is only read into a local variable (and main() would not be called automatically in the LiveConnect setup anyway).
So how about something like:
public class ListFiles {
public:
String getFiles() {
String result = "";
// [iterate over the files and add their names to result]
return result;
}
}
And in the JS code:
var Files = myObj.getFiles();
instead of
var Files = myObj.String;
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.
I am using an array of files.
String[] allFiles = new String[]{"real.xml", "fake.xml"};
I am getting this error that
java.nio.file.NoSuchFileException: C:\Users\rio\rio-workspace\real.xml
I am trying to run command to know where it is looking for the file. I came across this solution but it doesn't work with array.
System.out.println(allFiles.toAbsolutePath());
Would appreciate if someone give right command to know about this problem.
Thanks
Do it as follows:
import java.nio.file.Paths;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] allFiles = { "output.txt", "test.txt" };
// First method
for (String file : allFiles) {
System.out.println(Paths.get(file).toAbsolutePath());
}
// Second method (by using Stream)
Arrays.stream(allFiles).forEach(file -> System.out.println(Paths.get(file).toAbsolutePath()));
}
}
All relative files are filled in from the value in System.getProperty("user.dir");
An example
File[] thoseFiles = new File(System.getProperty("user.dir")).listFiles();
for (int i = 0; i < thoseFiles.length; i++) {
System.out.println(thoseFiles[i].getAbsolutePath());
}
Or if you chose to have the files in a folder
File[] thoseFiles = new File("ThatFolder").listFiles();
for (int i = 0; i < thoseFiles.length; i++) {
System.out.println(thoseFiles[i].getAbsolutePath());
}
This can be expanded with a Filefilter
File f=new File("C:/");
File fList[] = f.listFiles();
When i use this it list all system file as well as hidden files.
and this cause null pointer exception when i use it to show in jTree like this:
public void getList(DefaultMutableTreeNode node, File f) {
if(f.isDirectory()) {
DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
node.add(child);
File fList[] = f.listFiles();
for(int i = 0; i < fList.length; i++)
getList(child, fList[i]);
}
}
What should i do so that it do not give NullPointerException and show only non hidden and non system files in jTree?
Do this for hidden files:
File root = new File(yourDirectory);
File[] files = root.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return !file.isHidden();
}
});
This will not return hidden files.
As for system files, I believe that is a Windows concept and therefore might not be supported by File interface that tries to be system independent. You can use Command line commands though, if those exist.
Or use what #Reimeus had in his answer.
Possibly like
File root = new File("C:\\");
File[] files = root.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
Path path = Paths.get(file.getAbsolutePath());
DosFileAttributes dfa;
try {
dfa = Files.readAttributes(path, DosFileAttributes.class);
} catch (IOException e) {
// bad practice
return false;
}
return (!dfa.isHidden() && !dfa.isSystem());
}
});
DosFileAttributes was introduced in Java 7.
If running under Windows, Java 7 introduced DosFileAttributes which enables system and hidden files to be filtered. This can be used in conjunction with a FileFilter
Path srcFile = Paths.get("myDirectory");
DosFileAttributes dfa = Files.readAttributes(srcFile, DosFileAttributes.class);
System.out.println("System File? " + dfa.isSystem());
System.out.println("Hidden File? " + dfa.isHidden());
If you are trying to list all files in C:/ please keep in mind that there are other files also which are neither hidden nor system files, but that still won't open because they require special privileges/permissions. So:
String[] files = file.list();
if (files!=null) {
for (String f : files) open(f);
}
So just compare if the array is null or not and design your recursion in such a way that it just skips those files whose array for the list() function is null.
private void nodes(DefaultMutableTreeNode top, File f) throws IOException {
if (f.isDirectory()) {
File[] listFiles = f.listFiles();
if (listFiles != null) {
DefaultMutableTreeNode b1[] = new DefaultMutableTreeNode[listFiles.length];
for (int i = 0; i < b1.length; i++) {
b1[i] = new DefaultMutableTreeNode(listFiles[i].toString());
top.add(b1[i]);
File g = new File(b1[i].toString());
nodes(b1[i], g);
}
}
}
Here is the code I used to create a window file explorer using jtree.
I am a beginner in Java trying to work with Files and Directories. I wanted to create a program where I could change file names automatically while searching through all the child directories for file names that are not valid. I am actually trying to load a huge amount of files on to a server but the server settings do not allow file names containing special characters. To start with I was able to write the code where if I pass the path to a directory it renames all the files with invalid names in that directory:
public class reNaming {
public static String baseLoc = "C:/Users/Developer/Desktop/.../Data Cleanup";
public static void main(String[] args) {
//LinkedList<File> fileList = new LinkedList<File>();
File obj = new File(baseLoc);
int count = 0;
for (File file: obj.listFiles())
{
String origName = file.getName();
if (origName.contains("&") || origName.contains("#") || origName.contains("#"))
{
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("#", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+"/"+newName;
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
}
}
}
}
Now I want to do the same but only this time I want all the files to be reNamed even in the child directories. Can somebody please guide me how I can achieve that?
Recursion is your friend
/**Removes 'invalid' characters (&,#,#) from pathnames in the given folder, and subfolders, and returns the number of files renamed*/
public int renameDirectory(File base){
//LinkedList<File> fileList = new LinkedList<File>();
int count=0;//count the renamed files in this directory + its sub. You wanted to do this?
//Process each file in this folder.
for (File file: base.listFiles()){
String origName = file.getName();
File resultFile=file;
if (origName.contains("&") || origName.contains("#") || origName.contains("#")){
//I would replace the if statement with origName.matches(".*[&##].*") or similar, shorter but more error prone.
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("#", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+File.separator+newName;//having "/" hardcoded is not cross-platform.
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
resultFile=newFile;//not sure if you could do file=newFile, tired
}
//if this 'file' in the base folder is a directory, process the directory
if(resultFile.isDirectory()){//or similar function
count+=renameDirectory(resultFile);
}
}
return count;
}
Move the code you have to a utility method (e.g. public void renameAll(File f){}). Have a condition that checks if the file is a directory and recursively call your method with it's contents. After that do what you are currently doing.
public void renameAll(File[] files){
for(File f: files){
if(f.isDirectory){
renameAll(f.listFiles());
}
rename(f);
}
}
public void rename(File f){ }
It is a program (Java) that uses system calls to extract basic information related to the system.
Scan all the files and Display the name and path of the file with the maximum size
Can someone please help i am confused with the system calls.
THanks
Start by taking a look at java.io.File
Take a look at:
File#listFiles
File#length
The for statement
If you're very brave and have the time, you could also take a look at the File I/O API available in Java 7
This is what tou need. But you should read documentation about FILE API . http://docs.oracle.com/javase/7/docs/api/java/io/File.html
public class ListFiles
{
public static void main(String[] args)
{
// Directory path here
String path = ".";
String files="";
double maxBytes = 0;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile() && listOfFiles[i].length()>maxBytes)
{
maxBytes = listOfFiles[i].length()
files = listOfFiles[i].getName();
}
}
System.out.println(files);
}
}