I'm writing some code to get the latest file from a directory but the console doesn't display any result.
Here's the code I've written :
import java.io.File;
public class test {
public static File getLastModified(String directoryFilePath)
{
File directory = new File("C:\\New folder");
File[] files = directory.listFiles(File::isFile);
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (files != null)
{
for (File file : files)
{
if (file.lastModified() > lastModifiedTime)
{
chosenFile = file;
lastModifiedTime = file.lastModified();
System.out.println(file);
}
}
}
return chosenFile;
}
public static void main(String[] args) {}
}
You have to do 2 things,.
Need to call getLastModified() method in your main method
Scanner reading each line in the file and doing system. print calls? while (scanner.hasNextLine()) { System.out.println(blah blah blah); }
Simple. Done!
Related
I have a problem, i have this directory with 1k+ files and some folders. I need find the path of the files(which are in subdirectories) that starts with "BCM", but not only the first i find but every single file which start with that.
I tried looking at other answers about this topic but i couldn't find help,
tried using this code:
File dir = new File("K:\\Jgencs");
FilenameFilter filter = new FilenameFilter()
{
public boolean accept (File dir, String name)
{
return name.startsWith("BCM");
}
};
String[] children = dir.list(filter);
if (children == null)
{
System.out.println("No directory found");
}
else
{
for (int i = 0; i< children.length; i++)
{
String filename = children[i];
System.out.println(filename);
File h = new File(dir,filename);
System.out.println(h.getAbsolutePath()
[UPDATED] This is how you can achieve using plain Java and filter text from a variable passing as parameter:
Here is my directory: /tmp
And here is the code running:
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GetAllFilesInDirectory {
public static void main(String[] args) throws IOException {
String filter = "BCM";
List<File> files = listFiles("/tmp", new CustomerFileFilter(filter));
for (File file : files) {
System.out.println("file: " + file.getCanonicalPath());
}
}
private static List<File> listFiles(String directoryName, CustomerFileFilter fileFilter) {
File directory = new File(directoryName);
List<File> files = new ArrayList<>();
// Get all files from a directory.
File[] fList = directory.listFiles(fileFilter);
if(fList != null) {
for (File file : fList) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
files.addAll(listFiles(file.getAbsolutePath(), fileFilter));
}
}
}
return files;
}
}
class CustomerFileFilter implements FileFilter {
private final String filterStartingWith;
public CustomerFileFilter(String filterStartingWith) {
this.filterStartingWith = filterStartingWith;
}
#Override
public boolean accept(File file) {
return file.isDirectory() || file.isFile() && file.getName().startsWith(filterStartingWith);
}
}
This is the output:
file: /private/tmp/BCM01.txt
file: /private/tmp/BCM01
file: /private/tmp/subfolder1/BCM02.txt
Doing recursive calls to the method when finding a directory to also list the files form inside, and filtering by name the files before adding.
You want Files.walk:
try (Stream<Path> files = Files.walk(Paths.get("K:\\Jgencs"))) {
files.filter(f -> f.getFileName().toString().startsWith("BCM")).forEach(
file -> System.out.println(file));
}
I have a piece of code that iterates over all the files in a directory.
But I am stuck now at reading the content of the file into a String object.
public String filemethod(){
if (path.isDirectory()) {
files = path.list();
String[] ss;
for (int i = 0; i < files.length; i++) {
ss = files[i].split("\\.");
if (files[i].endsWith("txt"))
System.out.println(files[i]);
}
}
return String.valueOf(files);
}
Faced with a similar problem and wrote a code a while back. This will read the content of all files of a directory.
May require adjustments based on your file directories but its tried and tested code.Hope this helps :)
package FileHandling;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
public class BufferedInputStreamExample {
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
public void readFile(File folder) {
ArrayList<File> myFiles = listFilesForFolder(folder);
for (File f : myFiles) {
String path = f.getAbsolutePath();
//Path of the file(Optional-You can know which file's content is being printed)
System.out.println(path);
File infile = new File(path);
try {
fis = new FileInputStream(infile);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
String line = dis.readLine();
System.out.println(line);
}
} catch (IOException e) {
} finally {
try {
fis.close();
bis.close();
dis.close();
} catch (Exception ex) {
}
}
}
}
public ArrayList<File> listFilesForFolder(final File folder){
ArrayList<File> myFiles = new ArrayList<File>();
for (File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
myFiles.addAll(listFilesForFolder(fileEntry));
} else {
myFiles.add(fileEntry);
}
}
return myFiles;
}
}
Main method
package FileHandling;
import java.io.File;
public class Main {
public static void main(String args[]) {
//Your directory here
final File folder = new File("C:\\Users\\IB\\Documents\\NetBeansProjects\\JavaIO\\files");
BufferedInputStreamExample bse = new BufferedInputStreamExample();
bse.readFile(folder);
}
}
I would use following code:
public static Collection<File> allFilesInDirectory(File root) {
Set<File> retval = new HashSet<>();
Stack<File> todo = new Stack<>();
todo.push(root);
while (!todo.isEmpty()) {
File tmp = todo.pop();
if (tmp.isDirectory()) {
for (File child : tmp.listFiles())
todo.push(child);
} else {
if (isRelevantFile(tmp))
retval.add(tmp);
}
}
return retval;
}
All you need then is a method that defines what files are relevant for your usecase (for instance txt)
public static boolean isRelevantFile(File tmp) {
// get the extension
String ext = tmp.getName().contains(".") ? tmp.getName().substring(tmp.getName().lastIndexOf('.') + 1) : "";
return ext.equalsIgnoreCase("txt");
}
Once you have all the files, you can easily get all the text with a little hack in Scanner
public static String allText(File f){
// \\z is a virtual delimiter that marks end of file/string
return new Scanner(f).useDelimiter("\\z").next();
}
So now, using these methods you can easily extract all the text from an entire directory.
public static void main(String[] args){
File rootDir = new File(System.getProperty("user.home"));
String tmp = "";
for(File f : allFilesInDirectory(rootDir)){
tmp += allText(f);
}
System.out.println(tmp);
}
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadDataFromFiles {
static final File DIRECTORY = new File("C:\\myDirectory");
public static void main(String[] args) throws IOException {
StringBuilder sb = new StringBuilder();
//append content of each file to sb
for(File f : getTextFiles(DIRECTORY)){
sb.append(readFile(f)).append("\n");
}
System.out.println(sb.toString());
}
// get all txt files from the directory
static File[] getTextFiles(File dir){
FilenameFilter textFilter = (File f, String name) -> name.toLowerCase().endsWith(".txt");
return dir.listFiles(textFilter);
}
// read the content of a file to string
static String readFile(File file) throws IOException{
return new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())), StandardCharsets.UTF_8);
}
}
This question already has answers here:
Standard concise way to copy a file in Java?
(16 answers)
Closed 6 years ago.
I am trying to write a java program that will take two arguments, dirName and fileName. The program will search for all the files in dirName that end with .java and then concatenate them into a new folder called fileName. So far I have a method to search for .java files in dirName, I then put them in a file array called list but now I am struggling to iteratively add the files in this array to my new folder, fileName. Here is what I have so far:
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
public class TwoFiles {
File dir;
File name;
public TwoFiles(File dirName, File fileName) {
dir = dirName;
name = fileName;
}
public void setDir(File m) {
this.dir = m;
}
public File getDir() {
return dir;
}
public void setNewFolder(File n) {
this.name = n;
}
public File getNewFolder() {
return name;
}
public File[] Finder(File dir) {
dir = getDir();
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return name.endsWith(".java"); }
} );
}
public static void main(String[] args) {
File folder = null;
File newFolder = null;
Integer b = null;
TwoFiles tf = new TwoFiles(folder, newFolder);
folder = tf.getDir();
newFolder = tf.getNewFolder();
File[] list = tf.Finder(folder); //add to an array
//here is where I've been experimenting to add files in `list` to new folder, `fileName`.
for (File file : list)
{
FileInputStream inFile = new FileInputStream(file);
while ((b = inFile.read()) != -1)
newFolder.write(b);
inFile.close();
}
//copy files from array (list) into newFolder
}
}
Thanks for your time.
Your newFolder variable is of type File. You cannot write into this. I assume, your code does not even compile. You have to create an output stream in front of your loop:
FileOutputStream fos = new FileOutputStream( newFolder);
try
{
for (File file : list)
{
FileInputStream inFile = new FileInputStream(file);
while ((b = inFile.read()) != -1)
fos.write(b);
inFile.close();
}
}
finally
{
fos.close();
}
You can use the Apache Commons IO copyDirectory() with the IOFileFilter (for .java extensions) to copy your files from one directory to another. Before that you can ensure to create a new directory using forceMkdir() for your filename.
It's my version of your problem:
I created other constructor, where you can put only paths to directory/folder from you want concatenate files, and to file of concatenations result.
public class TwoFiles {
private File dir;
private File name;
public TwoFiles(File dirName, File fileName) {
dir = dirName;
name = fileName;
}
public TwoFiles(String dirName, String destinationFileName) throws IOException{
dir=new File(dirName);
if(!dir.isDirectory()){
throw new FileNotFoundException();//here your exception in case when dirName is file name instead folder name
}
name=new File(destinationFileName);
if(!name.exists()){
name.createNewFile();
}
}
public void setDir(File m) {
this.dir = m;
}
public File getDir() {
return dir;
}
public void setNewFolder(File n) {
this.name = n;
}
public File getNewFolder() {
return name;
}
public void concatenateFiles() throws IOException{
File[] files=dir.listFiles();
for(File file: files){
if(file.getName().endsWith(".java")){ //check is right file
prescribe(name, file);
}
}
}
/** prescribe file to new destination */
private void prescribe(File destination, File file) throws IOException {
FileInputStream inFile = new FileInputStream(file);
FileOutputStream writer=new FileOutputStream(destination, true); //true means next file will be write beginning from end of the file
int x;
while((x=inFile.read())!=-1){
writer.write(x);
}
String test="\n"; //next line in file
writer.write(test.getBytes());
writer.close();
inFile.close();
}
public static void main(String...strings){
String dirName="C/myApp/model/entity";
String fileName="C:/Users/Dell/Desktop/temp/test.java";
try {
new TwoFiles(dirName, fileName).concatenateFiles();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What i wanna do is to recursively search for some files on the external sd-card. The problem is that the code is looking ok, but (assuming .txt files) it only shows me 7 files out of 100+ that are being spread throughout folders.
The code is this:
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
void makelist(File file){
if(file.isFile()){
if(SimpleAdapter.getFileType(file)==null)
mis.add(file);
else if(SimpleAdapter.getFileType(file).equalsIgnoreCase("text"))
doc.add(file);
}else if(file.isDirectory()){
for(File f:file.listFiles())
makelist(f);
}
}
Any idea how could i make it run correctly?
Assuming you are building two lists (misc files and doc files), try with below code which all all files other than text files to misc and text files to doc.
if(SimpleAdapter.getFileType(file) == null || !SimpleAdapter.getFileType(file).equalsIgnoreCase("text"))
mis.add(file);
else
doc.add(file);
Not sure why it is not working for you. Tried a test program and it worked perfectly...
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileChecker
{
/**
* #param args
*/
public static void main(String[] args) {
SimpleAdapterTest adapter = new SimpleAdapterTest();
adapter.makelist(new File("C:\\MYFolder"));
adapter.showList();
}
}
class SimpleAdapterTest
{
List<File> mis = new ArrayList<File>();
List<File> doc = new ArrayList<File>();
public static String getFileType(File f)
{
String Name = f.getName();
if (f.getName().endsWith(".txt") || Name.endsWith(".TXT")
|| Name.endsWith(".inf") || Name.endsWith(".INF"))
return "text";
return null;
}
public void makelist(File file){
if(file.isFile()){
if(SimpleAdapterTest.getFileType(file)==null)
mis.add(file);
else if(SimpleAdapterTest.getFileType(file).equalsIgnoreCase("text"))
doc.add(file);
}else if(file.isDirectory()){
for(File f:file.listFiles())
makelist(f);
}
}
public void showList()
{
for(File miscFile : mis)
{
System.out.println("Misc files = " + miscFile.getName());
}
for(File docfile : doc)
{
System.out.println("Doc files = " + docfile.getName());
}
}
}
HI I want to write a java program by which I can delete all the files of my computer having a specific extension or character pattern in name.I also want to apply wild card character on the name of file.
Thanks in advance
For your program to be really useful you need to do some more thinking, but for a starter;
import java.io.File;
import java.util.regex.Pattern;
private static void walkDir(final File dir, final Pattern pattern) {
final File[] files = dir.listFiles();
if (files != null) {
for (final File file : files) {
if (file.isDirectory()) {
walkDir(file, pattern);
} else if (pattern.matcher(file.getName()).matches()) {
System.out.println("file to delete: " + file.getAbsolutePath());
}
}
}
}
public static void main(String[] args) {
walkDir(new File("/home/user/something"), Pattern.compile(".*\\.mp3"));
}
Sidenote (not an answer, but you didn't ask something): Be aware of recursion.
public void deleteFilesWithExtension(final String directoryName, final String extension) {
final File dir = new File(directoryName);
final String[] allFiles = dir.list();
for (final String file : allFiles) {
if (file.endsWith(extension)) {
new File(aDirectoryName + "/" + file).delete();
}
}
}