I am trying to rename to upper case all the files in a given directory. It does the whole thing but it doesn't do anything in the folder file names are still the same .
import java.io.File;
import java.io.IOException;
public class FileOps {
public static void main(String[] argv) throws IOException {
File folder = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
File f = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files"
+ listOfFiles[i].getName());
f.renameTo(new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files"
+ listOfFiles[i].getName().toUpperCase()
+ ".txt"));
}
}
System.out.println("Done");
}
}
It prints "Done" in the console but nothing is really done
In your if statement, you forgot to add ending separator:
if (listOfFiles[i].isFile()) {
File f = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files\\"// <- Missing separator
+ listOfFiles[i].getName());
f.renameTo(new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files\\"// <- Missing separator
+ listOfFiles[i].getName().toUpperCase()
+ ".txt"));
}
A proper implemntation would be:
if (listOfFiles[i].isFile())
listOfFiles[i].renameTo(new File(folder, listOfFiles[i].getName().toUpperCase()+ ".txt"));//not sure why this .txt
Be careful, the renameTo method is highly platform dependent. Read the Javadoc
You might use the following to check what is happening. Some small changes include using the File(parent,name) form to avoid having to determine and add the OS specific file path separator.
package com.example.renaming;
import java.io.File;
import java.io.IOException;
public class TestRename {
private static final String[] defaultArgs = { "C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files" };
private static TestRename me;
private static String[] arguments;
public static void main(String[] args) {
me = new TestRename();
if (args == null | args.length == 0) {
arguments = defaultArgs;
} else {
arguments = args;
}
me.doWork(arguments);
}
private void doWork(String[] arguments) {
int numFiles = 0;
File folder = new File(arguments[0]);
try {
System.out.println("Working on " + folder.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File[] fileList = folder.listFiles();
if (fileList == null) {
System.out.println("No files fould");
} else {
for (int i = 0; i < fileList.length; i++) {
System.out.println("File " + fileList[i].getName());
if (fileList[i].isFile()) {
numFiles++;
try {
String currentName = fileList[i].getName();
File parent = fileList[i].getParentFile();
String newName = currentName.toUpperCase() + ".txt";
System.out.println(" .. current = " + currentName);
System.out.println(" .. newname = " + newName);
// Avoids having to get the file path separator for an OS
File newFile = new File(parent, newName);
System.out.println(" .. new File = "
+ newFile.getCanonicalPath());
fileList[i].renameTo(newFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println("Done, found " + numFiles);
}
}
}
As pointed by ortis, you have missed to add "\" while naming files.
f.renameTo(new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files"
+ listOfFiles[i].getName().toUpperCase()
+ ".txt"));
executing this code over and over will result in adding .txt to the file names. You can consider using apache FileUtils for getting extention.
Making those changes to your code,
File folder = new File("/home/ubuntu/Desktop/pics");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles){
if(file.isFile()){
String fileName = FilenameUtils.removeExtension(file.getName()).toUpperCase() ;
String newPath = folder + File.separator + fileName+ "."+ FilenameUtils.getExtension(file.getName());
file.renameTo(new File(newPath));
}
}
Related
I've made a program that lists all file names in a desired directory of your extension choice. Now I want to and I don't know how to change it to list all files within sub-directories too. Do you have any ideas? Here's my code. Thanks!
import java.util.*;
import java.io.*;
public class Program {
public static void main(String str[]){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("1.Enter directory name:");
String adress = br.readLine();
System.out.println("2.Enter file extension:");
String exten = br.readLine();
File directory = new File(adress);
File[] f = directory.listFiles();
List<String> files = new ArrayList<String>();
List<String> valid = new ArrayList<String>();
List<String> names = new ArrayList<String>();
for(int i=0; i < f.length; i++){
if(f[i].isFile()){
files.add(f[i].getName());
}
}
for(int i=0; i < files.size(); i++){
if (files.get(i).endsWith(exten)){
valid.add(files.get(i));
}
}
for(int i=0; i < valid.size(); i++){
int pos = valid.get(i).lastIndexOf(".");
names.add(valid.get(i).substring(0, pos));
System.out.println(names.get(i));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
If you can use Java 7 or 8 you could use the FileVisitor, but in Java 7 it means writing more then one line of code. If not and you want to keep it simple, Apache Commons FileUtils may be your friend.
Collection<File> files = FileUtils.listFiles(path, new String[]{"xlxs"}, true);
I made this awhile back to find all of *.xls or *.xlsx in a directory.
Hope this will help you with your question.
public static List<String> fileSearch(String d){
List<String> filesFound = new ArrayList<String>();
File dir = new File(d);
try{
for(File file: dir.listFiles()){
if(file.isFile() && (file.getName().toLowerCase().endsWith(".xlsx") || file.getName().toLowerCase().endsWith(".xls"))){
long filesize = file.length();
long fileSize = filesize / 1024;
filesFound.add(d + "\\" + file.getName());
System.out.println("Added: " + d + "\\" + file.getName() + " " + fileSize + " KB" );
}else if(file.isDirectory() && !file.isHidden()){
System.out.println("Found Directory: " + file.getName());
filesFound.addAll(fileSearch(d + "\\" + file.getName()));
}else if(isRoot(file)){
//DO NOTHING
}
}
}catch(NullPointerException ex){
ex.printStackTrace();
}finally{
return filesFound;
}
}
private static boolean isRoot(File file){
File[] roots = File.listRoots();
for (File root : roots) {
if (file.equals(root)) {
return true;
}
}
return false;
}
What this does, it will search every file for a match and if it matches then it will add it to the array "filesFound" from there you can get all the paths of matched files. BUT for you, you would take out the .xlsx and .xls part and add in your ext.
fileSearch(String d, String ext)
and change the if then to:
if(file.isFile() && file.getName().toLowerCase().endsWith(ext))
ALSO i have it outputting when ever it finds a match with the file size next to it. The file size is just a visual aid and does not get included in the array.
I have developed an application that read how many files are there in a java package inside the java project and count the line of code in those individual files to for example in a java project if there are 2 packages having 4 individual files then total files read will be 4 and if those 4 files having 10 piece of lines of code in each file then 4*10 is total 40 lines of code in overall project ...below is my piece of code
private static int totalLineCount = 0;
private static int totalFileScannedCount = 0;
public static void main(final String[] args) throws FileNotFoundException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
Map<File, Integer> result = new HashMap<File, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
List<File> files = getFileListing(directory);
// print out all file names, in the the order of File.compareTo()
for (File file : files) {
// System.out.println("Directory: " + file);
getFileLineCount(result, file);
//totalFileScannedCount += result.size(); //saral
}
System.out.println("*****************************************");
System.out.println("FILE NAME FOLLOWED BY LOC");
System.out.println("*****************************************");
for (Map.Entry<File, Integer> entry : result.entrySet()) {
System.out.println(entry.getKey().getAbsolutePath() + " ==> " + entry.getValue());
}
System.out.println("*****************************************");
System.out.println("SUM OF FILES SCANNED ==>" + "\t" + totalFileScannedCount);
System.out.println("SUM OF ALL THE LINES ==>" + "\t" + totalLineCount);
}
}
public static void getFileLineCount(final Map<File, Integer> result, final File directory)
throws FileNotFoundException {
File[] files = directory.listFiles(new FilenameFilter() {
public boolean accept(final File directory, final String name) {
if (name.endsWith(".java")) {
return true;
} else {
return false;
}
}
});
for (File file : files) {
if (file.isFile()) {
Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
totalFileScannedCount ++; //saral
try {
for (lineCount = 0; scanner.nextLine() != null; ) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
lineCount++;
}
}
} catch (NoSuchElementException e) {
result.put(file, lineCount);
totalLineCount += lineCount;
}
}
}
}
/**
* Recursively walk a directory tree and return a List of all Files found;
* the List is sorted using File.compareTo().
*
* #param aStartingDir
* is a valid directory, which can be read.
*/
static public List<File> getFileListing(final File aStartingDir) throws FileNotFoundException {
validateDirectory(aStartingDir);
List<File> result = getFileListingNoSort(aStartingDir);
Collections.sort(result);
return result;
}
// PRIVATE //
static private List<File> getFileListingNoSort(final File aStartingDir) throws FileNotFoundException {
List<File> result = new ArrayList<File>();
File[] filesAndDirs = aStartingDir.listFiles();
List<File> filesDirs = Arrays.asList(filesAndDirs);
for (File file : filesDirs) {
if (file.isDirectory()) {
result.add(file);
}
if (!file.isFile()) {
// must be a directory
// recursive call!
List<File> deeperList = getFileListingNoSort(file);
result.addAll(deeperList);
}
}
return result;
}
/**
* Directory is valid if it exists, does not represent a file, and can be
* read.
*/
static private void validateDirectory(final File aDirectory) throws FileNotFoundException {
if (aDirectory == null) {
throw new IllegalArgumentException("Directory should not be null.");
}
if (!aDirectory.exists()) {
throw new FileNotFoundException("Directory does not exist: " + aDirectory);
}
if (!aDirectory.isDirectory()) {
throw new IllegalArgumentException("Is not a directory: " + aDirectory);
}
if (!aDirectory.canRead()) {
throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
}
}
but the issue is that it also count the white space lines while calculating the line of code for the individual files , which it should not , please advise what modifications I need to do in my program so that it should not count the white spaces while calculating the line of code for the individual files .
The idea that was coming to my mind was just compares the read string with "", and count if not equals to "" (empty) like if(!readString.trim().equals("")) lineCount++
Please advise for this
Suggestions:
Scanner has a hasNextLine() method which you should use. I would use it as the condition of a while loop.
Then get the line inside the while loop by calling nextLine() just once inside of the loop.
Again call trim() on your Strings that are read in. I still don't see your attempt at this in the latest code update!
A key concept when calling methods on Strings is that they are immutable, and the methods called on them do not change the underlying String, and trim() is no different: The String that it is called on is unchanged, but the String returned by the method is changed, and in fact is trimmed.
String has an isEmpty() method that you should call after trimming the String.
So don't do:
try {
for (lineCount = 0; scanner.nextLine() != null; ) {
if(!readString.trim().equals("")) lineCount++; // updated one
}
} catch (NoSuchElementException e) {
result.put(file, lineCount);
totalLineCount += lineCount;
}
Instead do:
int lineCount = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
lineCount++;
}
}
I am trying to add some files to a ZIP file, it creates the file but does not add anything into it.
Code 1:
String fulldate = year + "-" + month + "-" + day + "-" + min;
File dateFolder = new File("F:\\" + compname + "\\" + fulldate);
dateFolder.mkdir();
String zipName = "F:\\" + compname + "\\" + fulldate + "\\" + fulldate + ".zip";
zipFolder(tobackup, zipName);
My function:
public static void zipFolder(File folder, String name) throws Exception {
byte[] buffer = new byte[18024];
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(name));
FileInputStream in = new FileInputStream(folder);
out.putNextEntry(new ZipEntry(name));
int len;
while((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
in.close();
out.close();
}
Edit: I found the problem, it was just having trouble writing files from the C:\ drive into a ZIP in the F:\ drive
You can't zip folders, only files. To zip folders, you have to add all the subfiles manually. I wrote this class that does the job. You can have it for free :)
The usage would be this:
List<File> sources = new ArrayList<File>();
sources.add(tobackup);
Packager.packZip(new File(zipName), sources);
Here is the class:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Packager
{
public static void packZip(File output, List<File> sources) throws IOException
{
System.out.println("Packaging to " + output.getName());
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(output));
zipOut.setLevel(Deflater.DEFAULT_COMPRESSION);
for (File source : sources)
{
if (source.isDirectory())
{
zipDir(zipOut, "", source);
} else
{
zipFile(zipOut, "", source);
}
}
zipOut.flush();
zipOut.close();
System.out.println("Done");
}
private static String buildPath(String path, String file)
{
if (path == null || path.isEmpty())
{
return file;
} else
{
return path + "/" + file;
}
}
private static void zipDir(ZipOutputStream zos, String path, File dir) throws IOException
{
if (!dir.canRead())
{
System.out.println("Cannot read " + dir.getCanonicalPath() + " (maybe because of permissions)");
return;
}
File[] files = dir.listFiles();
path = buildPath(path, dir.getName());
System.out.println("Adding Directory " + path);
for (File source : files)
{
if (source.isDirectory())
{
zipDir(zos, path, source);
} else
{
zipFile(zos, path, source);
}
}
System.out.println("Leaving Directory " + path);
}
private static void zipFile(ZipOutputStream zos, String path, File file) throws IOException
{
if (!file.canRead())
{
System.out.println("Cannot read " + file.getCanonicalPath() + " (maybe because of permissions)");
return;
}
System.out.println("Compressing " + file.getName());
zos.putNextEntry(new ZipEntry(buildPath(path, file.getName())));
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4092];
int byteCount = 0;
while ((byteCount = fis.read(buffer)) != -1)
{
zos.write(buffer, 0, byteCount);
System.out.print('.');
System.out.flush();
}
System.out.println();
fis.close();
zos.closeEntry();
}
}
Enjoy!
EDIT: To check if the program is still busy, you can add the three lines I marked with a (*)
EDIT 2: Try the new code. On my platform, it runs correct (OS X). I'm not sure but, there might be some limited read permissions for files in Windows in AppData.
See also ZeroTurnaround's Zip library. It has such features as (citation):
pack and unpack directories recursively
iterate through ZIP entries
I'll add another way using Java 7 NIO FileSystem. It uses the fact that JAR files are actually ZIP:
static public void addToZip(Path zip, Path file) throws IOException {
Map<String,String> env = new HashMap<>();
env.put("create", "false"); // We don't create the file but modify it
URI uri = URI.create("jar:file:"+zip.toString());
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path f = zipfs.getPath(file.getFileName().toString());
Files.copy(file, f, StandardCopyOption.REPLACE_EXISTING);
}
}
I have searched and searched for an example of how to do this, but I have yet to find one.
I have a log file and in this log file it will have a list of files. I then need to move the files that were scanned in to a quarantined folder and retain directory structure. So far I have the following code:
public static void main(String[] args) throws FileNotFoundException, IOException
{
String logPath = "C:\\apache-ant-1.8.2\\build\\LogFiles\\DoScan.log";
String safeFolder = "C:\\apache-ant-1.8.2\\build\\Quaratined";
ArrayList<File> files = new ArrayList<File>();
BufferedReader br = new BufferedReader(new FileReader( logPath ));
String line = null;
while ((line = br.readLine()) != null)
{
Pattern pattern = Pattern.compile("'[a-zA-Z]:\\\\.+?'");
Matcher matcher = pattern.matcher( line );
if (matcher.matches())
{
}
if (matcher.find())
{
String s = matcher.group();
s = s.substring(1, s.length()-1);
files.add(new File(s));
System.out.println("File found:" + files.get(files.size() - 1));
}
}
for (File f : files)
{
// Make sure we get a file indeed
if (f.exists())
{
if (!f.renameTo(new File(safeFolder, f.getName())))
{
System.out.println("Moving file: " + f + " to " + safeFolder);
System.err.println("Unable to move file: " + f);
}
}
else
{
System.out.println("Could not find file: " + f);
}
}
}
}
This works and successfully moves the files, but it does not maintain directory structure.
Any help is much appreciated.
Try something like this:
public static void main(String[] args) throws IOException {
String logPath = "/tmp/log";
String safeFolder = "/tmp/q";
ArrayList<File> files = new ArrayList<File>();
BufferedReader br = new BufferedReader(new FileReader(logPath));
String line = null;
while ((line = br.readLine()) != null) {
files.add(new File(line));
System.out.println("File found:" + files.get(files.size() - 1));
}
String root = "/tmp/" ;
for (File f : files && f.isFile()) {
if (f.exists()) {
File destFile = new File(safeFolder, f.getAbsolutePath().replace(root,""));
destFile.getParentFile().mkdirs();
if (!f.renameTo(destFile)) {
System.out.println("Moving file: " + f + " to " + safeFolder);
System.err.println("Unable to move file: " + f);
}
} else {
System.out.println("Could not find file: " + f);
}
}
}
here is a code to concatenate all files from a folder.
it works well but i modified it to delete files after concatenation and this function is not working coze i don't know how to declare in main method
Any help will be appreciated thank you very much.
import java.io.*;
import java.io.File.*;
public class ConcatenatedFiles {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Concatenated-file/concat.txt"));
File file = new File("C:/Target");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println("Processing " + files[i].getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(files[i]
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
}
pw.close();
System.out.println("All files have been concatenated into concat.txt");
File directory = new File("C:/Target");
// Get all files in directory
File[] files = directory.listFiles();
for (File file : files)
{
// Delete each file
if (!file.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+file);
}
}
}
}
First, make sure you have enough permission to be able to delete the contents in c:\target directory.
Second, if that directory contains subdirectories, you will need to delete all the files in each subdirectory first before you can perform a file.delete() on the subdirectory. You can do recursive deletion like this:-
public boolean deleteDirectory(File path) {
if (path.exists()) {
for (File file : path.listFiles()) {
if (file.isDirectory()) {
deleteDirectory(file);
}
else {
file.delete();
}
}
}
return path.delete();
}
Then, you can call deleteDirectory("C:/Target"); to perform the recursive deletion.
I am guessing this is something you copied from elsewhere. You declare File[] files twice - the second time just do
File directory = new File("C:/Target");
// Get all files in directory
files = directory.listFiles();
for (File toDelete : files)
{
// Delete each file
if (!toDelete.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+toDelete);
}
}
You could try just moving your delete to your first loop... like this,
import java.io.*;
import java.io.File.*;
public class ConcatenatedFiles {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Concatenated-file/concat.txt"));
File file = new File("C:/Target");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
File currentFile = files[i];
System.out.println("Processing " + currentFile.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(currentFile));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
if (!currentFile.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+ currentFile.getName());
}
}
pw.close();
System.out.println("All files have been concatenated into concat.txt");
}