Access path of a file in java array - java

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

Related

What is the meaning of LinkOption.NOFOLLOW_LINKS and when to use it?

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.

Java listFiles is not showing the current running file in its listing

so I have this program where I want to get the current list of files in the directory where the Java file is executing.
Here is the call:
File q1 = new File(System.getProperty("user.dir"));
File[] listOfFiles = sanitiseFileChecker(q1.listFiles());
And this is the sanitiseFileChecker method:
public void sanitiseFileChecker(File[] list){
List<File> files = new ArrayList<File>(Arrays.asList(list));
for(int i = 0; i < files.size(); i++){
System.out.println(files.get(i).getName());
}
}
This works perfectly except... my output is
Name.class
FOLDER
FILEA
FILEB
FILEC
But Name.java does not appear... I am confused why it is not being detected, can Java not detect a file listing when a java program is running?
This worked like expected to me:
import java.io.*;
public class ShowFiles {
public static void main(String[] args) {
File userDir = new File(System.getProperty("user.dir"));
File[] files = userDir.listFiles();
System.out.println("Files in " + userDir.getAbsolutePath());
for (File file : files) {
System.out.println("\t" + file.getName());
}
}
}
Sorry guys, my fault, I realised a mistake with concurrent removal from the list itself which caused the indexes to get mixed up.

Convert a file array to string array JAVA

I need some help.
I use this code to get the files in a folder as an array .
String fileDir = Directorty;
File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.html");
files = dir.listFiles(fileFilter);
But I want to write a file with only the files in that folder and not the path.
The result is:
[C:\Askeladden-17-12-2014\.html, C:\Askeladden-17-12-2014\barnetv.html, C:\Askeladden-17-12-2014\britiskebiler.html, C:\Askeladden-17-12-2014\danser.html, C:\Askeladden-17-12-2014\disipler.html, C:\Askeladden-17-12-2014\donald.html, C:\Askeladden-17-12-2014\ekvator.html, C:\Askeladden-17-12-2014\engelskspraak.html]
But I want to have it without the path
C:\Askeladden-17-12-2014\
I have been looking around the webs to find some answers, but no luck.
Using this:
strFiles = Arrays.toString(files);
Gives a string presented as an array with [] in each end, and I am not able to get
strFiles.replace("C:\\Askleladden" + date +"\\", "");
to work.
You have to iterate the files array and call getName() for each file:
String[] names = new String[files.length];
for (int i = 0; i < files.length; i++) {
names[i] = files[i].getName();
}
Java 1.8, if you want get as List, just remove cast and to array
String[] files = (String[])Arrays.asList(dir.listFiles(filefilter))
.stream().map(x->x.getName())
.collect(Collectors.toList())
.toArray();
Please find the solution below with proper comments.
import java.io.File;
import java.io.FileFilter;
public class fileNames {
public static void main(String args[]){
//Get the Directory of the FOLDER
String fileDir = "/MyData/StudyDocs/";
// Save it in a File object
File dir = new File(fileDir);
//FileFilter fileFilter = new WildcardFileFilter("*.html");
//Capture the list of Files in the Array
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++){
System.out.println(files[i].getName());
}
}
}
Use Files getName() method:
File file = new File("myFolder/myFile.png");
System.out.println(file.getName()); //Prints out myFile.png

Is it possible to store files of a folder in dynamic array in Java [duplicate]

This question already has answers here:
Finding common Files from two arrays
(2 answers)
Closed 9 years ago.
I am trying to find same name files in two folders.
I used File and listed names of file in two array list.
then i added common name files in two folders to a new arraylist and going to apply diff to find if these files are different or not.
As i have only stored name of files in Array List, i can't apply operation on those files directly.
Someone told me that by the use of dynamic array one can save files in Java...
My code till now with help of some great friends :
import java.io.File;
import java.util.*;
public class ListFiles1
{
public static void main(String[] args)
{
String path1 = "C:\\Users\\hi\\Downloads\\IIT Typing\\IIT Typing";
String path2 = "C:\\Users\\hi\\Downloads\\IIT Typing\\IIT Typing";
File folder1 = new File(path1);
File folder2 = new File(path2);
String[] f1=folder1.list();
File[] listOfFiles1 = folder1.listFiles();
File[] listOfFiles2 = folder2.listFiles();
ArrayList<String> fileNames1 = new ArrayList<>();
ArrayList<String> fileNames2 = new ArrayList<>();
for (int i = 0; i < listOfFiles1.length; i++)
{
if (listOfFiles1[i].isFile())
{
fileNames1.add(listOfFiles1[i].getName());
// System.out.println(f1[i] + " is a file");
}
}
for (int j = 0; j < listOfFiles2.length; j++)
{
if (listOfFiles2[j].isFile())
{
fileNames2.add(listOfFiles2[j].getName());
}
}
ArrayList<String> commonfiles = new ArrayList<>();
for (int i = 0; i < listOfFiles1.length; i++)
{
for (int j = 0; i < listOfFiles2.length; j++)
{
String tempfilename1;
String tempfilename2;
tempfilename1=fileNames1.get(i);
tempfilename2 = fileNames2.get(j);
if(tempfilename1.equals(tempfilename2))
{
commonfiles.add(tempfilename1);
System.out.println(commonfiles);
}
}
}
}
}
Rather then having an ArrayList of Strings of the file names, just have an ArrayList of Files
List<File> filesList1 = Arrays.asList(folder1.listFiles());
List<File> filesList2 = Arrays.asList(folder2.listFiles());
Then when comparing if they have the same name then do your check of if it is a file and has the same name, then you have the reference to the File object and not just the name so you can read the files and see if they are the same.
for (File f1 : filesList1)
{
if(f1.isFile())
{
for (File f2 : filesList2)
{
if(f2.isFile() && f1.getName().equals(f2.getName))
{
commonfiles.add(f1.getName());
System.out.println(f1.getName());
}
}
}
}
This could be done way more efficiently with sets though
I'm not sure what your question actually is here, but I suggested that you use:
Set<String> dir1Files = new HashSet<String>();
Set<String> dir2Files = new HashSet<String>();
// load the sets with the filenames by iterating the File.listFiles() value, and using File.isFile() and File.getName() - just like your existing code
dir1Files.retainAll(dir2Files);
// now dir1Files contains the filenames that are the same in both directories
And if you need to work with the file itself, just recreate the File object:
File dir1File = new File(folder1, filename);
import java.io.File;
public class FileNameMatcher
{
public static void main(String[] args)
{
File folder1 = new File("C:/Users/pappu/Downloads");
File folder2 = new File("C:/Users/pappu");
for(String fileFromFolderOne:folder1.list())
{
for(String fileFromFolderTwo:folder2.list())
{
if(fileFromFolderOne.equals(fileFromFolderTwo))
{
System.out.println("match found");
System.out.println("file name is ===>>>"+fileFromFolderOne);
}
}
}
}
}

Failed to access Java code from XUL/JavaScript

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;

Categories

Resources