Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
File folder = new File("C:/Path/Dir");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
String csvFile = file.getName();
System.out.println(csvFile);
}
}
Output:
1.csv
2.csv
3.csv
There is 3 files in my Dir so after i get all 3 of them how can i use the first one in my file reader:
//File reader
Path path = Paths.get(csvFile);
int lineCount = (int) Files.lines(path).count();
If you are specific to 1st file only then just use listOfFiles[0].getName() to get fileName.
If you are to going to take path of a file that satisfy specific condition then you can use like below :
File folder = new File("C:/Path/Dir");
File[] listOfFiles = folder.listFiles();
String csvFile = null;
for (File file : listOfFiles) {
if (file.isFile() && <condition>) {
csvFile = file.getName();
System.out.println(csvFile);
break;
}
}
listOfFiles[0] should get you the first element.
Please read some tutorials on java arrays :
https://www.javatpoint.com/array-in-java
There:
File folder = new File("C:/Path/Dir");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
String csvFile = file.getName();
System.out.println(csvFile);
// Reader (for all files)
try {
FileReader reader = new FileReader(file);
} catch (IOException e) { /* TODO */ }
// Line count (for all files)
int lineCount = (int) Files.lines(file.toPath()).count();
}
}
// Reader (for first file)
File firstFile = listOfFiles[0];
try {
FileReader reader = new FileReader(file);
} catch (IOException e) { /* TODO */ }
// Line count (for first file)
int lineCount = (int) Files.lines(firstFile.toPath()).count();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
then i use
listOfFiles[i] in my file reader
Sorry for been dump for a while )
When you are only interested in files (not directories or whatever) you can already specify this criteria in your File.listFiles call:
File[] files=new File("c:/tmp").listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isFile();
}
});
Or with java 8 Lambdas
File[] files=new File("c:/tmp").listFiles((f)->{return f.isFile();});
In the list of files you can pick the first one as you would do to pick the first element of an array:
System.out.println("First file:"+(files.length>0?files[0]:" no files"));
Simple, you have all files in an array of the File as
File[] listOfFiles = folder.listFiles();
So you can directly access the first file by index (index starts with 0) as follows
Path path = Paths.get(listOfFiles[0].getName());
int lineCount = (int) Files.lines(path).count();
You need to figure out two thing:first read only file not folder;second which file is the fisrt file.The follow code assume you want read file and get first file by file name in dictionary order:
private static void readFirstFile(String path) throws Exception {
File folder = new File(path);
File[] files = folder.listFiles(File::isFile);
if (null == files || files.length < 3) {
return;
}
Arrays.sort(files, Comparator.comparing(File::getName));
List<String> lines = FileUtils.readLines(files[0], "UTF-8");
lines.forEach(System.out::println);
}
Related
I've got an image folder in my resources folder and there are pictures stored.
Now I want an Array in my Java Class who has stored the names of each Picture in the folder. Later I want to test if a picture name equals a specific word, but that can I handle by myself. I just dont know, how to make the 'PictureName' Array.
I am using Spring boot with Java.
File folder = new File("C:\\path\\to\\your\\folder\\");
List<File> files = Arrays.asList(folder.listFiles());
Insert the path to the folder that contains all your images in the first line.
In files List you will find the list of all the images in your folder in objects of type File.
Every File object has the method getName() that will return the name of the image.
Try somethings like this(Check if f is file( because it can be dictionary):
File folder = new File("yourPathTofolder");
File[] listOfFiles = folder.listFiles();
for (File f: listOfFiles) {
if (f.isFile()) {
System.out.println("File " + f.getName());
}
}
It can be done easily:
File folder = new File("your_path");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if(file.isFile()){
System.out.println("File Name:" + file.getName());
}
}
You can use below code:
First provide your folder path, that will contain all the images.
File folder = new File("your/path");
Store all files in File type array variable.
File[] listOfFiles = folder.listFiles();
Iterate over variable to get filename(s)
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else {
System.out.println("Not a File..");
}
}
Full code
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else {
System.out.println("Not a File..");
}
}
Hope that helps.
I followed this question:
Now in my case i have 720 files named in this way: "dom 24 mar 2013_00.50.35_128.txt", every file has a different date and time. In testing phase i used Scanner, with a specific txt file, to do some operations on it:
Scanner s = new Scanner(new File("stuff.txt"));
My question is:
How can i reuse scanner and read all 720 files without having to set the precise name on scanner?
Thanks
Assuming you have all the files in one place:
File dir = new File("path/to/files/");
for (File file : dir.listFiles()) {
Scanner s = new Scanner(file);
...
s.close();
}
Note that if you have any files that you don't want to include, you can give listFiles() a FileFilter argument to filter them out.
Yes, create your file object by pointing it to a directory and then list the files of that directory.
File dir = new File("Dir/ToYour/Files");
if(dir.isDir()) {
for(File file : dir.listFiles()) {
if(file.isFile()) {
//do stuff on a file
}
}
} else {
//do stuff on a file
}
You can try this in this way
File folder = new File("D:\\DestFile");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()&&(file.getName().substring(file.getName().lastIndexOf('.')+1).equals("txt"))) {
// Scanner
}
}
File file = new File(folderNameFromWhereToRead);
if(file!=null && file.exists()){
File[] listOfFiles = file.listFiles();
if(listOfFiles!=null){
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
// DO work
}
}
}
}
Im trying to list all the files in a particular folder of my android emulator and i keep getting null answer.
Heres my code:
File sdCardRoot = Environment.getExternalStorageDirectory();
File[] file= new File(sdCardRoot+"path");
for (File f : file.listFiles()) {
if (f.isFile())
String name = f.getName();
}
This doesnt seem to work dont know why.
I've split the function in two parts, first function gets all the files in the given path and the second function gets the filenames from the file array.
public File[] GetFiles(String DirectoryPath) {
File f = new File(DirectoryPath);
f.mkdirs();
File[] file = f.listFiles();
return file;
}
public ArrayList<String> getFileNames(File[] file){
ArrayList<String> arrayFiles = new ArrayList<String>();
if (file.length == 0)
return null;
else {
for (int i=0; i<file.length; i++)
arrayFiles.add(file[i].getName());
}
return arrayFiles;
}
change
File[] file= new File(sdCardRoot+"path");
with
File[] file= new File(sdCardRoot, "path");
and make sure the directory path exits
Just Check this:
List<File> files = getListFiles(new File("YOUR ROOT"));
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")) {
inFiles.add(file);
}
}
}
return inFiles;
Since sdCardRoot is instance of File, sdCardRoot+"path" will return the same thing as sdCardRoot.toString() + "path".
However, calling file.toString() returns file name, but not absolute path. You need to call sdCardRoot.getAbsolutePath() + "path".
Also, make sure that you have allowed the emulator to use a certain amount of memory for external storage.
So I have the following code (which has been shamelessly copied from a tutorial so I can get the basics sorted), in which it asks the player to load their game (text-based adventure game)
but I need a way to display all the saved games in the directory. I can get the current directory no worries. Here is my code:
public void load(Player p){
Sleep s = new Sleep();
long l = 3000;
Scanner i = new Scanner(System.in);
System.out.println("Enter the name of the file you wish to load: ");
String username = i.next();
File f = new File(username +".txt");
if(f.exists()) {
System.out.println("File found! Loading game....");
try {
//information to be read and stored
String name;
String pet;
boolean haspet;
//Read information that's in text file
BufferedReader reader = new BufferedReader(new FileReader(f));
name = reader.readLine();
pet = reader.readLine();
haspet = Boolean.parseBoolean(reader.readLine());
reader.close();
//Set info
Player.setUsername(name);
Player.setPetName(pet);
Player.setHasPet(haspet);
//Read the info to player
System.out.println("Username: "+ p.getUsername());
s.Delay(l);
System.out.println("Pet name: "+ p.getPetName());
s.Delay(l);
System.out.println("Has a pet: "+ p.isHasPet());
} catch(Exception e){
e.printStackTrace();
}
}
}
File currentDirectory = new File(currentDirectoryPath);
File[] saveFiles = currentDirectory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
You can first get a File object for the directory:
File ourDir = new File("/foo/bar/baz/qux/");
Then by checking ourDir.isDirectory() you can make sure you don't accidentally try to work on a file. You can handle this by falling back to another name, or throwing an exception.
Then, you can get an array of File objects:
File[] dirList = ourDir.listFiles();
Now, you may iterate through them using getName() for each and do whatever you need.
For example:
ArrayList<String> fileNames=new ArrayList<>();
for (int i = 0; i < dirList.length; i++) {
String curName=dirList[i].getName();
if(curName.endsWith(".txt"){
fileNames.add(curName);
}
}
This should work:
File folder = new File("path/to/txt/folder");
File[] files = folder.listFiles();
File[] txtFiles = new File[files.length];
int count = 0;
for(File file : files) {
if(file.getAbsolutePath().endsWith(".txt")) {
txtFiles[count] = file;
count++;
}
}
It should be pretty self explanatory, you just need to know folder.listFiles().
To trim down the txtFiles[] array use Array.copyOf.
File[] finalFiles = Array.copyOf(txtFiles, count);
From the docs:
Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.
My question is that I want to send pdf files through web service with condition that only 1mb of files are taken from that folder containing many files.
Please help me to resolve this question.I am new to web service.
Ask me again if it not clear.
Thanks In Advance.
The following method will return a list of all the files whose total size is <= 1Mb
public List<File> getFilesList(){
File dirLoc = new File("C:\\Temp");
List<File> validFilesList = new ArrayList<File>();
File[] fileList;
final int fileSizeLimit = 1024000; // Bytes
try {
// select all the files whose size <= 1Mb
fileList = dirLoc.listFiles(new FilenameFilter() {
public boolean accept(final File dirLoc, final String fileName) {
return (new File(dirLoc + "\\" + fileName).length() <= fileSizeLimit);
}
});
long sizeCtr = fileSizeLimit;
for(File file : fileList){
if(file.length() <= sizeCtr){
validFilesList.add(file);
sizeCtr = sizeCtr - file.length();
if(sizeCtr <= 0){
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
validFilesList = new ArrayList<File>();
} finally {
fileList = null;
}
return validFilesList;
}
Well, I dont know if I have understood your requirements correctly and if this would help your problem but you can try this java solution for filtering the files from a directory.
You will get a list of files and then you can use the web-service specific code to send these files
File dirLoc = new File("C:\\California");
File[] fileList;
final int fileSize = 1024000;
try {
fileList = dirLoc.listFiles(new FilenameFilter() {
public boolean accept(final File dirLoc, final String fileName) {
return (new File(dirLoc+"\\"+fileName).length() > fileSize);
}
});
} catch (Exception e) {
e.printStackTrace();
} finally {
fileList = null;
}
This should work.
If you just require filenames, replace the File[] with String[] and .listFiles() with list()
I cannot say much about the performance though. For a small list of files it should work pretty fast.
I am not sure if this is what you want but you can pick the files and check their size by :
java.io.File file = new java.io.File("myfile.txt");
file.length();
File.length()Javadoc
Send files whose size is 1 Mb.