I want to know the directory structure of a particular directory on the webserver. I can login through putty (by providing userid and password) but i want to do the code in java in my local system and print the directory structure for the same. I did LS -R in putty to get the same but it is very huge so i want this same to print in java console.
Can anyone please suggest in how to do?
Edit:
Let me explain below is the code for getting the directory structure
static void showDir(int indent, File file) throws IOException {
for (int i = 0; i < indent; i++) {
System.out.print('-');
System.out.println(file.getName());
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++){
showDir(indent + 4, files[i]);
}
}
}
but this prints for my local system. I want this to be work for remote server. I have the IP of server.
Expanding on Chris Kuehl's comment about SSH-ing with Java, you may want to look into one of these:
JSch
Ganymed SSH-2
I would assume (but I haven't looked into it) that with one of these one could feasibly write code that SSH's into a machine, then executes commands on it, capturing the output.
It may be as simple as loading one of those libraries, writing code that connects via SSH to the machine, executes and captures the output of: cd your_dir, ls -R, then prints it.
Related
I am writing a desktop application in Java to quickly find files. I have used the exec command in Java to run powershell to do this, as Java's os.walk method seems to be much slower. Right now it takes about 5 minutes to generate a text file that lists the contents of all files on my computer (a total of around 440,000 files).
This is fine, but the problem I have is that I have no way of updating this list of files. So if I change a few files in my file system and want to update my file list, I can't do so quickly (i.e. incrementally). Instead, I have to generate the file list all over from scratch.
I know you can use git-bash to create a locate database (using updatedb). Now this is an awesome solution, but the application I'm trying to create may be used by people who don't have that installed. So I'd like to do it using default apps provided with Windows (i.e. powershell, or natively in Java). I am trying to make this app easy to use, so I don't want the user to have to install a bunch of other dependencies.
The following code shows how to use Java and avoid Powershell altogether. It builds an array in memory and writes it to a text file (467,000 files listed) all in under 30 seconds!
Run the following code in Main or wherever you want. It calls the createFileList method.
List<Path> pathsArrayList = new ArrayList<>();
Path rootPath_obj;
rootPath_obj = Paths.get(this.configMap.get("root_path"));
createFileList(rootPath_obj);
Here's the tree stream traversal code:
public void createFileList(Path path_in) throws IOException, AccessDeniedException {
try (DirectoryStream<Path> mystream = Files.newDirectoryStream(path_in)) {
for (Path entry : mystream) {
if (Files.isDirectory(entry)) {
createFileList(entry);
}
pathsArrayList.add(entry);
}
}
catch (AccessDeniedException ex) {
// Do nothing, just move on to the next file
}
}
Now write the file to save for later. This is the listing of all files within the root path tree.
System.out.println("Writing database...");
try (FileWriter writer = new FileWriter(this.configMap.get("db_path"))) {
for(Path pth: pathsArrayList){
writer.write(pth.toString() + System.lineSeparator());
}
}
System.out.println("...database written.");
I'm working on a java application which is supposed to load in images from the same directory that the .jar file will be in. The code below is what I currently have, and it works fine in Windows (in the workspace I'm using and in the .jar file's directory, wherever I put it). However, when I try to run the .jar file in OS X, it doesn't work. I get a null pointer exception. Is there something that I'm missing? or some formatting thing I'm not aware of?
String dir = System.getProperty("user.dir");
File folder = new File(dir+"/");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String name = listOfFiles[i].getName();
String fileType = name.substring(name.length()-3, name.length());
if (fileType.equals("jpg")){
File file = new File(dir+"/"+name);
listMPs.add(new MusicPanel(file));
base.add(listMPs.get(count));
base.add(listMPs.get(count).switchLabel);
if(count==0){
base.add(listMPs.get(0).firstSwitchLabel);
}
assignIndexes();
assignMLs();
count++;
}
}
}
Is there something that I'm missing?
Perhaps you missed that applications should not be storing loose files in the program installation directory. In fact, Sun/Oracle has gone to extreme lengths with applets and JWS launched apps. to ensure that even trusted ones cannot discover that location. Put the files in a more accessible place. A common place is a sub-directory of user.home.
You should be using File.separator instead of manually supplying /s in your paths. Java will format the paths according to the current OS implementation.
I use this piece of code to find XML files that another part of my program creates in a given directory:
String fileName;
File folder = new File(mainController.XML_FILES_LOCATION);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
fileName = listOfFiles[i].getName();
if (fileName.endsWith(".xml")) {
Document readFile = readFoundXmlFile(fileName);
if (readFile != null) {
boolean postWasSuccesful = mainController.sendXmlFile(readFile, fileName);
reproduceXmlFile(readFile, fileName, postWasSuccesful);
deleteXmlFile(fileName);
}
}
}
}
What it does is that it reads every XML file that gets placed in the given directory, it sends it to an URL and it copies it to a subdirectory (either 'sent' or 'failed' based on the boolean postWasSuccedful) and deletes the original so it won't be sent again.
In Windows this works as expected, but I've transferred the working code to a Linux machine and all of a sudden it get's in this loop of sending bla.xml and a second later sent\bla.xml and again a second later sent\sent\bla.xml followed by sent\sent\sent\bla.xml, etc.
Why is Linux deciding for itself that listFiles() is recursive?? And, better, how to prevent that? I can add an extra check in the if-statement looking for files ending with .xml that there isn't a directory-char allowed in the fileName, but that's a workaround I don't want as the amount of files in the pick-up directory will never be high whereas the amount of files in the sent subdirectory can get quite high after a while and I wouldn't want this piece of code to become slow
My psychic powers tell me that reproduceXmlFile() builds the target pathname using a hard-coded backslash ("\"), and therefore you're actually creating files with backslashes in their names.
You need to use File.separator rather than that hard-coded "\". Or use something like new File("sent", fileName).toString() to generate your output pathnames.
(Apologies if I'm wrong!)
I am trying to create a method that displays a list of files in a given directory. This works fine for normal directories (on disk) but when I enter a url my list of files is null.
public void getListOfFiles(String folderLocation){
File folder = new File(folderLocation);
File[] listFiles = folder.listFiles();
for(int i = 0; i < 10; i++){
System.out.println(listFiles[i]);
}
}
I think my problem is because the File 'folder' is removing one of the '/' in my folderLocation (http://...)
I have tried using URL and URI but have had no luck! Can anyone help?
First of all, File won't work for this as it's not networking-aware.
Secondly, in general there's no mechanism to list files over plain HTTP. If the HTTP server gives you some kind of a listing page when you present it with the URL, you'll have to download the page using, for example, URLConnection and parse it yourself.
To list files over FTP, you could use FTPClient from Apache Commons Net.
I have some sort of batch program that should pick up a file from a directory and process it.
Since this program is supposed to:
run on JDK 5,
be small (no external libraries)
and fast! (with a bang)
...what is the best way to only pick one file from the directory - without using File.list() (might be hundreds of files)?
In Java 7 you could use a DirectoryStream, but in Java 5, the only ways to get directory entries are list() and listFiles().
Note that listing a directory with hundreds of files is not ideal but still probably no big deal compared to processing one of the files. But it would probably start to be problematic once the directory contains many thousands of files.
Use a FileFilter (or FilenameFilter) written to accept only once, for example:
File dir = new File("/some/dir");
File[] files = dir.listFiles(new FileFilter() {
boolean first = true;
public boolean accept(final File pathname) {
if (first) {
first = false;
return true;
}
return false;
}
});
It seems from what you said that you want to process every file in the directory once (including files that get added to the directory). You can do the following: set a monitor on the directory that generates notifications when files are added. you then process each file that you get notified about. Since you use JDK 5 , i suggest using jpathwatch . note that you need to make sure the file writing has finished before trying to process it. after starting the monitor to insure you will be processing every new file, make a one time usage of file listing to process the current content.
Edit: My implementation made use of .list() as you said it wouldn't but It may hold some value anyways :)
If you look at the File implementation public String[] list() method seems to have less overhead than File[] listFiles(). So fastest should be
String[] ss = myDir.list();
File toProcess = null;
for(int i = o ; i< ss.length ; i++){
toProcess = new File(myDir.list()[i], myDir));
if(toProcess.isFile())break;
}
From File.class
public File[] listFiles() {
String[] ss = list();
if (ss == null) return null;
int n = ss.length;
File[] fs = new File[n];
for (int i = 0; i < n; i++) {
fs[i] = new File(ss[i], this);
}
return fs;
}
If one look at the class class FileSystem which it boils down to for filesystem access there is only the list method so there seems to be no other way in "pure" JAVA to select a file than to list them all in a String array.
There is no good solution here on Java 1.5, you can use a filter to get only 1 file, but then java will only return one file but parse over all of them anyways. If you don't need the actual file object you could try something like Runtime.getRuntime().exec("dir") split the returned string on \n and print out the first line :-P