When I run this program, it finds the file that starts with yyyy and returns the files correctly; however, it skips my.File.exists() and goes to else "File Name Change Failed". I have been looking at this code for a long time..what noob mistake am I making?
//Searches the path for files
String pathToScan =("C:\\Users\\desktop\\test\\");
String target_file ;
File folderToScan = new File(pathToScan);
File[] listOfFiles = folderToScan.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
target_file = listOfFiles[i].getName();
if (target_file.startsWith("YYYY")){
System.out.println("-----------------------------------------------");
System.out.println("Match Found: "+ target_file);
//if the target file exists
if(myFile.exists()){
long lastmod = myFile.lastModified();
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD");
String lastmodi = format.format(new Date(lastmod));
File newfile = new File("C:\\Users\\desktop\\test\\"+lastmodi+".csv");
//If rename successful, then print success with file location
if(myFile.renameTo(newfile)){
System.out.println("File Name Change Successful, New File Created:" + newfile.getPath());
}
else{
System.out.println("File Name Change Failed");
}
}
I think you are referring a wrong file in myFile. The following code is working for me with added code. The other reasons can be that you don't have the Access to Write in C:\Users\desktop\test\ directory and/or that directory doesn't exist.
String pathToScan = ("C:\\Users\\<User Name>\\desktop\\test\\");
String target_file;
File folderToScan = new File(pathToScan);
File myFile = null; // Added this
File[] listOfFiles = folderToScan.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
target_file = listOfFiles[i].getName();
myFile = listOfFiles[i]; // Added this
if (target_file.startsWith("YYYY")) {
System.out
.println("-----------------------------------------------");
System.out.println("Match Found: " + target_file);
// if the target file exists
if (myFile.exists()) {
long lastmod = myFile.lastModified();
SimpleDateFormat format = new SimpleDateFormat(
"YYYY-MM-DD");
String lastmodi = format.format(new Date(lastmod));
File newfile = new File(
"C:\\Users\\<User Name>\\desktop\\test\\"
+ lastmodi + ".csv");
// If rename successful, then print success with file
// location
if (myFile.renameTo(newfile)) {
System.out
.println("File Name Change Successful, New File Created:"
+ newfile.getPath());
} else {
System.out.println("File Name Change Failed");
}
}
}
}
}
Related
I am trying to implement POP3 protocol functionalities and i want to use the file system (directories and text files in it) as a database to store emails. To do so, i need to renumber the .txt files (email1.txt, email2.txt,..) every time i access the database, to check weather any of the emails got deleted. Let's say email2.txt has been deleted, that means in the next transaction all emails will be renumbered and email3.txt will get renamed to email2.txt, email4 becomes email3 ans so on. and if none of them is deleted then all files should remain unchanged
I tried using following code, but it does not work. However, it works fine with windows. i know, renaming a file is OS dependant.
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
int i = 0;
for(File file1:filesInDir) {
i++;
String oldName = file1.getName();
oldName = absolutePath + "/" + oldName;
File oldFile=new File(oldName);
String newName = "email" + i + ".txt";
newName = absolutePath + "/" + newName;
File newFile =new File(newName);
oldFile.renameTo(newFile);
}
Hello I made this change to your code:
public static void main(String[] args) {
String absolutePath = "/Users/jucepho/Desktop/ReaderPaths/src/other/";
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
int i = 0;
for(File file1:filesInDir) {
i++;
String oldName = file1.getName();
oldName = absolutePath + File.separator+ oldName;
File oldFile=new File(oldName);
String newName = "email" + i + ".txt";
newName = absolutePath + File.separator+ newName;
File newFile =new File(newName);
oldFile.renameTo(newFile);
}
}
It renamed all my files in my directory to email1.txt email2.txt etc....
it should work i tested it on Ubuntu :)
Well I was thinking you could look for all files and see if they exist and do whatever you want look something like this :O ofcourse i haven't finished it but maybe it could help you =)
public static void main(String[] args) {
String absolutePath = "/Users/jucepho/Desktop/src/other/";
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
List<File> filesDirectory = Arrays.asList(filesInDir);
List<Integer> numbersUsed = new ArrayList<Integer>();
for(File files2: filesDirectory ){
String nameFile = files2.getName();
System.out.println(nameFile);
String regex = "email.\\.txt";
boolean dosItMatch = nameFile.matches(regex);
if(dosItMatch){
String number = "\\d+";
numbersUsed.add(Integer.valueOf(regex.replace("email", "").replace("\\.txt", "")));
}
System.out.println(dosItMatch);
}
System.out.println(numbersUsed);
int i = 0;
for(File file1:filesInDir) {
i++;
String oldName = file1.getName();
oldName = absolutePath + File.separator+ oldName;
File oldFile=new File(oldName);
String newName = "email" + i + ".txt";
newName = absolutePath + File.separator+ newName;
File newFile =new File(newName);
oldFile.renameTo(newFile);
}
}
Finally , i got rid of it by just sorting (filesInDir) array first.
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
Arrays.sort(filesInDir);
int i = 0;
for(File file1:filesInDir) {
i++;
String oldName = file1.getName();
s.getBasicRemote().sendText("+OK "+oldName);
oldName = absolutePath + "/"+ oldName;
File oldFile=new File(oldName);
String newName = "email" + i + ".txt";
newName = absolutePath + "/"+ newName;
s.getBasicRemote().sendText("+OK "+newName);
File newFile =new File(newName);
oldFile.renameTo(newFile);
}
I need help in renaming all files and folders in a directory and add a character in front of there original name.
This is a method to rename a single folder:
File from = new File(sdcard,".DCIM");
File to = new File(sdcard,"DCIM");
from.renameTo(to);
So, something like:
String path = Environment.getExternalStorageDirectory().toString()+"/MyDir";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
file[i].renameTo(file[i].getName() + "x");
}
EDIT:
To change a file name, it might be more clear to add a temporary variable:
String name = file[i].getName();
name = name.substr(0, name.length() - 1);
file[i].renameTo(name);
Go to the root folder and iterate over it. Just check if the the folder you are accessing is a directory or not and you can write the same logic in between for every folder.
public static void renameFile(String path) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
if (list == null)
return;
for (File f : list) {
if (f.isDirectory()) {
File from = new File(f,"."+f.getName());
File to = new File(f,f.getName());
from.renameTo(to);
renameFile(f.getCanonicalPath());
} else {
System.out.println("File:" + f.getAbsoluteFile());
}
}
}
public static void main(String[] args) throws IOException {
//Root path within which you want to change the folder names
renameFile("c:\rootPath");
}
Just check if this helps you.
How to search a particular folder for a file name, that is input by the user. In my program the file is an excel spreadsheet. So if i basically use:
Scanner kbReader = new Scanner(System.in);
String fileName = kbReader.nextLine();
How would i search and open the corresponding file with the name fileName.
You need to use regular expression to match your file name like filename.matches("*"+expectedfilename+"*.xls")) on List of file names taken from directory.
String fileName = null;
File folder = new File("your/directory/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
fileName = listOfFiles[i].getName();
if(fileName.matches("*"+expectedfilename+"*.xls"))){ // put regex here
// do your code here and
// if you want to open do operation on file then file object
File file = listOfFiles[i];
}
}
}
Try this
File dir = new File("F:/");
File[] allFileName = dir.listFiles();
for (int i = 0; i < allFileName.length; i++) {
String filename = allFileName[i].getName()
if (allFileName[i].isFile()) {
if (filename.endsWith(".xls"))
System.out.println("This is a excel file with name " + filename);
}
}
I want to read values from csv files, and order them in a table (console output).
How can I output all files in a folder and read all content in this files, and get filename while reading files with the content in it? I have so far only this, but I can't become the filename in right way, I become only the last filename and not the content of this file.
public static List<Objekt> run() throws IOException {
String path2 = "D:\\folder\\files";
File folder = new File(path2);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++){
if (listOfFiles[i].isFile()){
files = listOfFiles[i].getName();
if (files.endsWith(".csv")){
files = files.replace(".csv", "");
System.out.println(files);
}
}
}
List<Objekt> lines = new ArrayList<Objekt>();
String csvString = "D:\\folder\\files\\file1.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
Objekt objekt = null;
String[] hdr = null;
int l_count = 0;
br = new BufferedReader(new FileReader(csvString));
while ((line = br.readLine()) != null) {
if (l_count == 0) {
hdr = line.split(cvsSplitBy);
}
else{
String[] temp = line.split(cvsSplitBy);
for (int i = 0; i < temp.length; i++) {
objekt = new Objekt();
objekt.setTimestamp(hdr[i] + "\t" + temp[0] + "\t"
+ temp[i] + "\t" + files + "\n");
lines.add(objekt);
}
System.out.println(lines);
}
l_count++;
}
br.close();
return lines;
}
This is what I become (I get only that filename, which is at the end of the folder).
>tr_klue 06.03.2014 11:30 1389 outfilename
>tr_klue_lo 06.03.2014 12:00 1889 outfilename
but I need all filenames in this folder with corresponding content and save these in subfolder with filename and datetime with time when this was read, like:
tr_klue 06.03.2014 11:30 1389 outfilename
>tr_klue_lo 06.03.2014 12:00 1889 outfile1
>tr_klue 06.03.2014 12:30 100 props2
>tr_klue_lo 06.03.2014 13:00 89 colorak
Can you please give me some suggestions in which way to go?
If I understand your question, you need to first build a List of files and then iterate it -
File[] fileArray = folder.listFiles();
List<String> files = new ArrayList<String>(); // <-- A list of files
for (int i = 0; i < fileArray.length; i++)
{
if (fileArray[i].isFile())
{
String fileName = fileArray[i].getName();
if (fileName.endsWith(".csv")) // <-- does it end in ".csv"?
{
files.add(fileName); // <-- Add the file to the List.
}
}
}
// Now files contains the matching fileNames...
for (String fileName : files) {
// Add code here to use each fileName
System.out.println(fileName.replace(".csv", ""));
}
I am using "Files.copy" to copy files from one directory to another. 1 file will work, but when transferring multiple files, the contents of the copied files are the same, but the names are different. Please ignore bad naming. I am just quickly testing.
private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.showOpenDialog(null);
PathFile = fc.getSelectedFile().getAbsolutePath();
files = fc.getSelectedFiles();
int i=files.length;
System.out.print(i);
filesPath = Arrays.toString(files);
txtPath.setText(PathFile);
}
private void btnMoveActionPerformed(java.awt.event.ActionEvent evt) {
InputStream inStream = null;
OutputStream outStream = null;
String text = txtPath.getText();
String[] list = filesPath.split(",");
//String extension = filename.substring(filename.lastIndexOf('.'), filename.length());
String destPath = txtDest.getText();
try {
for(int i = 0; i<list.length; i++){
String filenamePre = list[i]
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "");
String filename = filenamePre.substring(filenamePre.lastIndexOf('\\'), filenamePre.length());
System.out.println(filename);
File afile = new File(text);
//File bfile = new File(destPath+"\\file1"+extension);
File bfile = new File(destPath + filename);
Path pa = afile.toPath();
Path pb = bfile.toPath();
//inStream = new FileInputStream(afile);
//outStream = new FileOutputStream(bfile);
//byte[] buffer = new byte[1024];
//int length;
//copy the file content in bytes
// while ((length = inStream.read(buffer)) > 0) {
// outStream.write(buffer, 0, length);
//}
//inStream.close();
//outStream.close();
Files.copy(pa, pb, REPLACE_EXISTING);
//delete the original file
//afile.delete();
}
System.out.println("File(s) copied successful!");
System.out.println();
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
private void txtPathActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnOpenDestActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
//guiMove frame = new guiMove();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(null);
PathDest = fc.getSelectedFile().getAbsolutePath();
txtDest.setText(PathDest);
}
shouldn't the getText method be in your loop when you retrieve the new file?
You are transferring only one file multiple times.
File afile = new File(text);
Source (text) is not changing in loop.
i am not sure what is your filePath content
String[] list = filesPath.split(",");
if you have two text box ( source directory and Destination directory) to get the source and destination .
Then you can get list of files from source like this.
File[] fList = new File(sDir).listFiles();
and loop through flist to get the files like this.
public void fileCopy(String sourceDir , String destDir) throws IOException{
File sDir = new File(sourceDir);
if (!sDir.isDirectory()){
// throw error
}
File dDir = new File(destDir);
if (!dDir.exists()){
dDir.mkdir();
}
File[] files = sDir.listFiles();
for (int i = 0; i < files.length; i++) {
File destFile = new File(dDir.getAbsolutePath()+File.separator+files[i].getName().replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "")
.replace(" ", ""));
// destFile.createNewFile();
Files.copy(files[i], destFile);
}
}