Duplicate results in recursion, connected database - java

I have a database connected that I am retrieving and storing local files and directories in. It works properly except when I run this segment, it will duplicate some of the results and store them. I believe the issue is in the way that I am grabbing them here, but I am not sure how to remedy it.
public static void Recursion(File dir, int dirid) {
for (java.io.File file : dir.listFiles()) {
if (file.isDirectory()) {
saveDir(dir, file);
} else if (file.isFile()) {
if (dirid == 0) {
saveDir(dir, file.getParentFile());
} // Begin Recursion, File
BoFile file1 = new BoFile();
file1.setFileName(file.getName());
file1.setFileType(file.getName().substring(file.getName().lastIndexOf('.') + 1).trim());
file1.setFileSize(new Long(file.length()).doubleValue() / 1024 + "MB");
file1.setFilePath(file.getPath());
file1.setDirNameId(dirid);
FileDAO fileDAO = new FileDAOImpl();
int id = fileDAO.insertFile(file1);
logger.info("New File: " + file.getName() + " ID = " + id);
}
}
}
private static void saveDir(File dir, File file) { // // Begin Recursion, Dir
Dir directory = new Dir();
directory.setDirName(file.getName());
directory.setDirNumberofFiles(dir.listFiles().length);
directory.setDirSize(new Long(dir.length()).doubleValue() / 1024 + "MB");
directory.setDirpath(dir.getPath());
DirDAO dirDAO = new DirDAOImpl();
int id = dirDAO.insertDir(directory);
logger.info("New Directory, " + file.getName() + " ID = " + id);
Recursion(file, id);
}

Related

How to increment the filename number if the file exists

How can I increment the filename if the file already exists?
Here's the code that I am using -
int num = 0;
String save = at.getText().toString() + ".jpg";
File file = new File(myDir, save);
if (file.exists()) {
save = at.getText().toString() + num + ".jpg";
file = new File(myDir, save);
num++;
}
This code works, but only two files are saved, like file.jpg and file2.jpg.
This problem is to always initialize num = 0, so if file exists, it saves file0.jpg and does not check whether file0.jpg exists.
So, to code work. You should check until it is available:
int num = 0;
String save = at.getText().toString() + ".jpg";
File file = new File(myDir, save);
while(file.exists()) {
save = at.getText().toString() + (num++) + ".jpg";
file = new File(myDir, save);
}
Try this:
File file = new File(myDir, at.getText().toString() + ".jpg");
for (int num = 0; file.exists(); num++) {
file = new File(myDir, at.getText().toString() + num + ".jpg");
}
// Now save/use your file here
In addition to the first answer, I made some more changes:
private File getUniqueFileName(String folderName, String searchedFilename) {
int num = 1;
String extension = getExtension(searchedFilename);
String filename = searchedFilename.substring(0, searchedFilename.lastIndexOf("."));
File file = new File(folderName, searchedFilename);
while (file.exists()) {
searchedFilename = filename + "(" + (num++) + ")" + extension;
file = new File(folderName, searchedFilename);
}
return file;
}
int i = 0;
String save = at.getText().toString();
String filename = save +".jpg";
File f = new File(filename);
while (f.exists()) {
i++;
filename =save+ Integer.toString(i)+".jpg";
f = new File(filename);
}
f.createNewFile();
You can avoid the code repetition of some of the answers here by using a do while loop
Here's an example using the newer NIO Path API introduced in Java 7
Path candidate = null;
int counter = 0;
do {
candidate = Paths.get(String.format("%s-%d",
path.toString(), ++counter));
} while (Files.exists(candidate));
Files.createFile(candidate);
Kotlin version:
private fun checkAndRenameIfExists(name: String): File {
var filename = name
val extension = "pdf"
val root = Environment.getExternalStorageDirectory().absolutePath
var file = File(root, "$filename.$extension")
var n = 0
while (file.exists()) {
n += 1
filename = "$name($n)"
file = File(root, appDirectoryName + File.separator + "$filename.$extension")
}
return file
}
Another simple logic solution to get the unique file name under a directory using Apache Commons IO using WildcardFileFilter to match the file name and get the number of exists with the given name and increment the counter.
public static String getUniqueFileName(String directory, String fileName) {
String fName = fileName.substring(0, fileName.lastIndexOf("."));
Collection<File> listFiles = FileUtils.listFiles(new File(directory), new WildcardFileFilter(fName + "*", IOCase.INSENSITIVE), DirectoryFileFilter.DIRECTORY);
if(listFiles.isEmpty()) {
return fName;
}
return fName.concat(" (" + listFiles.size() + ")");
}
This is the solution I use to handle this case. It works for folders as well as for files.
var destination = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyFolder")
if (!destination.exists()) {
destination.mkdirs()
} else {
val numberOfFileAlreadyExist =
destination.listFiles().filter { it.name.startsWith("MyFolder") }.size
destination = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"MyFolder(${numberOfFileAlreadyExist + 1})"
)
destination.mkdirs()
}
Having needed to solve this problem in my own code, I took Tejas Trivedi's answer, made it work like Windows when you happen to download the same file several times.
// This function will iteratively to find a unique file name to use when given a file: example (###).txt
// More or less how Windows will save a new file when one already exists: 'example.txt' becomes 'example (1).txt'.
// if example.txt already exists
private File getUniqueFileName(File file) {
File originalFile = file;
try {
while (file.exists()) {
String newFileName = file.getName();
String baseName = newFileName.substring(0, newFileName.lastIndexOf("."));
String extension = getExtension(newFileName);
Pattern pattern = Pattern.compile("( \\(\\d+\\))\\."); // Find ' (###).' in the file name, if it exists
Matcher matcher = pattern.matcher(newFileName);
String strDigits = "";
if (matcher.find()) {
baseName = baseName.substring(0, matcher.start(0)); // Remove the (###)
strDigits = matcher.group(0); // Grab the ### we'll want to increment
strDigits = strDigits.substring(strDigits.indexOf("(") + 1, strDigits.lastIndexOf(")")); // Strip off the ' (' and ').' from the match
// Increment the found digit and convert it back to a string
int count = Integer.parseInt(strDigits);
strDigits = Integer.toString(count + 1);
} else {
strDigits = "1"; // If there is no (###) match then start with 1
}
file = new File(file.getParent() + "/" + baseName + " (" + strDigits + ")" + extension); // Put the pieces back together
}
return file;
} catch (Error e) {
return originalFile; // Just overwrite the original file at this point...
}
}
private String getExtension(String name) {
return name.substring(name.lastIndexOf("."));
}
Calling getUniqueFileName(new File('/dir/example.txt') when 'example.txt' already exists while generate a new File targeting '/dir/example (1).txt' if that too exists it'll just keep incrementing number between the parentheses until a unique file is found, if an error happens, it'll just give the original file name.
I hope this helps some one needing to generate a unique file in Java on Android or another platform.
This function returns the exact new file with an increment number for all kind of extensions.
private File getFileName(File file) {
if (file.exists()) {
String newFileName = file.getName();
String simpleName = file.getName().substring(0, newFileName.indexOf("."));
String strDigit = "";
try {
simpleName = (Integer.parseInt(simpleName) + 1 + "");
File newFile = new File(file.getParent() + "/" + simpleName + getExtension(file.getName()));
return getFileName(newFile);
}
catch (Exception e){
}
for (int i=simpleName.length()-1; i>=0; i--) {
if (!Character.isDigit(simpleName.charAt(i))) {
strDigit = simpleName.substring(i + 1);
simpleName = simpleName.substring(0, i+1);
break;
}
}
if (strDigit.length() > 0) {
simpleName = simpleName + (Integer.parseInt(strDigit) + 1);
}
else {
simpleName += "1";
}
File newFile = new File(file.getParent() + "/" + simpleName + getExtension(file.getName()));
return getFileName(newFile);
}
return file;
}
private String getExtension(String name) {
return name.substring(name.lastIndexOf("."));
}

Java program, int i (i=0) default value is being used despite it increasing by 1 each loop

I am creating a JAVA program to copy certain folders to a new location automatically, to do this I created a function with a loop to use the same function for each given folder source and destination. The problem is that the function will just copy the first folder to the new location multiple times instead of copying it once then copying the next folder. The folder locations are held in a string array and a specific one is selected by changing value [i]. Each time the function loops [i] increases but the loop does not select the [i] value as well as the next folder to copy.
Is anyone able to help me with this, the code i am working with is below, Thanks.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Application {
static String[] saves = {
"C:\\Users\\Lucas\\Documents\\My Games\\Halo",
"C:\\Users\\Lucas\\Documents\\My Games\\Terraria",
"C:\\Users\\Lucas\\Documents\\My Games\\Borderlands 2",
"C:\\Users\\Lucas\\Documents\\My Games\\Rocket League"
};
private static int i = 1;
File source = new File(saves[i]);
static File folder = new File("Saves\\");
File dest = new File(String.valueOf(folder) + "\\" + source.getName());
private void Start() throws IOException {
MakeDirectory(folder);
Copy();
}
private void Copy() throws IOException {
copyFileUsingJava7Files(source, dest);
Add();
}
private void Add() throws IOException {
i++;
System.out.println("Value of i = " + i);
System.out.println("");
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
if (!dest.exists()) {
System.out.println("Copying files from: " + "'" + source + "'");
System.out.println("");
copyFolder(source, dest);
System.out.println("File copied");
} else {
copyFolder(source, dest);
}
}
private static void copyFolder(File source, File dest) throws IOException {
if (source.isDirectory()) {
if (!dest.exists()) {
dest.mkdir();
System.out.println("Directory created :: " + dest);
}
String files[] = source.list();
for (String file : files) {
File srcFile = new File(source, file);
File destFile = new File(dest, file);
copyFolder(srcFile, destFile);
}
} else {
if (source.lastModified() > dest.lastModified()) {
Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied :: " + dest);
} else {
System.out.println("A newer version exists of: " + "'" + dest + "'");
}
}
}
private static void MakeDirectory(File folder) {
if (!folder.exists()) {
System.out.println("Creating directory: " + "'" + folder + "'");
folder.mkdir();
System.out.println("Directory created");
} else {
System.out.println("Directory already exists: " + "'" + folder + "'");
}
}
public static void main(String[] args) throws IOException {
Application app = new Application();
int l;
for (l = 0; l < 3; l++) {
app.Start();
}
}
}
It doesn't look like you're ever changing the source field after setting it initially. You're setting it to the second file, but then not changing it later. Incrementing i won't automatically update source because source is just a File.
Also, you're starting with i = 1. In Java, arrays are zero-indexed, which means that the first item in the array is actually item 0, so you should be starting with i = 0 instead.
You have to reinitialize File source each time, you increase i. Otherwise, the source won't be changed.
Since i is a static variable, all objects share the same variable. Since you are incrementing the i during each app.Start() method, at the end of calling 5 times, its value is 5. Consequently you get the output as 5 in all your sys outs. Thats the point of static.

Writing GPX file to sdcard from geopoints (ArrayList)

My application tracks the distance and shows the result in km on the screen. I save the geopoints in an ArrayList. I’d like to export the geopoints as a GPX track file to my sdcard.
I tried https://sourceforge.net/projects/gpxparser/. But after the command GPXParser p = new GPXParser(); my app crashes. (I couldn’t find out how to “instantiate the GPXParser class”, maybe that’s why it didn’t work).
Importing GPX files works flawless with this approach http://android-coding.blogspot.de/2013/01/get-latitude-and-longitude-from-gpx-file.html
Could anyone point me in a direction or give me a hint. I’ve search a lot, but couldn’t find anything I could get to work.
Update!
I've found a solution. Maybe not perfect, but it works.
To save my track, I use the following from my Map-Activity.
Maybe some has a better solution :-).
public void saveRoute(String filename) {
Toast.makeText(this, mTrace.size() + "", Toast.LENGTH_SHORT).show();
String fileName = filename;
// routeFile = new File(getFilesDir(), FILENAME);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/kml");
myDir.mkdirs();
File file = new File(myDir, fileName + ".gpx");
savegpx gpxFile = new savegpx();
try {
file.createNewFile();
gpxFile.writePath(file, fileName, mTrace);
// Log.i(TAG, "Route Saved " + file.getName());
} catch (Exception e) {
Log.e("WritingFile", "Not completed writing" + file.getName());
}
}
Separate class
public class savegpx {
private static final String TAG = savegpx.class.getName();
public savegpx() {
}
/**
* Writes locations to gpx file format
*
* #param file file for the gpx
* #param n name for the file
* #param points List of locations to be written to gpx format
*/
public static void writePath(File file, String n, ArrayList<GeoPoint> points) {
final Context applicationContext= MainActivity.getContextOfApplication();
String header = "<gpx creator=\"Off-Road Tracker\" version=\"1.1\" xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n";
String metadata = " <metadata>\n" + " <time>1900-01-01T00:00:00Z</time>" + "\n </metadata>";
String name = " <trk>\n <name>" + n + "</name>\n <trkseg>\n";
String segments = "";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
List<String> stockList = new ArrayList<String>();
for (int i = 0; i < points.size(); i++) {
stockList.add(" <trkpt lat=\"" + (points.get(i)).getLatitude() + "\" lon=\"" + (points.get(i)).getLongitude() + "\">\n <ele>" +(points.get(i).getAltitude()) + "</ele>\n <time>" + df.format(new Date()) + "Z</time>\n </trkpt>\n");
}
segments +=stockList;
segments = segments.replace(",","");
segments = segments.replace("[","");
segments = segments.replace("]","");
Toast.makeText(applicationContext, segments, Toast.LENGTH_LONG).show();
String footer = " </trkseg>\n </trk>\n</gpx>";
try {
FileWriter writer = new FileWriter(file);
writer.append(header);
writer.append(metadata);
writer.append(name);
writer.append(segments);
writer.append(footer);
writer.flush();
writer.close();
Log.i(TAG, "Saved " + points.size() + " points.");
} catch (IOException e) {
//Toast.makeText(mapsActivity.getApplicationContext(),"File not found",Toast.LENGTH_SHORT);
Log.e(TAG, "Error Writting Path", e);
}
}
}

How to find count of files inside a folder in svn

I want to find the count of files inside the svn. i know how to check is it a file or directory.
try {
nodeKind = repository.checkPath("", -1);
} catch (SVNException ex) {
Logger.getLogger(Reassignscreen.class.getName()).log(Level.SEVERE, null, ex);
}
if (nodeKind == SVNNodeKind.NONE) {
System.err.println("There is no entry at '" + url + "'.");
commitClient.doMkDir(new SVNURL[]{SVNURL.parseURIDecoded(url)}, "New Folder");
}
Like this is there any way to retrieve the count of files inside the svn.
Use this code it will help you,
public class DisplayRepositoryList{
static int xmlfilecount = 0;
static ArrayList<String> imagefoldercheck = new ArrayList<String>();
public static void displayrepositorytree(String url, String name, String password) {
xmlfilecount =0;
SVNSetupLibrary.setupLibrary();
SVNRepository repository = null;
try {
repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
} catch (SVNException svne) {
System.err.println("error while creating an SVNRepository for location '" + url + "': " + svne.getMessage());
// System.exit(1);
}
ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(name, password);
repository.setAuthenticationManager(authManager);
try {
SVNNodeKind nodeKind = repository.checkPath("", -1);
if (nodeKind == SVNNodeKind.NONE) {
System.err.println("There is no entry at '" + url + "'.");
// System.exit(1);
} else if (nodeKind == SVNNodeKind.FILE) {
System.err.println("The entry at '" + url + "' is a file while a directory was expected.");
// System.exit(1);
}
System.out.println("Repository Root: " + repository.getRepositoryRoot(true));
System.out.println("Repository UUID: " + repository.getRepositoryUUID(true));
System.out.println("");
imagefoldercheck = new ArrayList<String>();
listEntries(repository, "");
} catch (SVNException svne) {
System.err.println("error while listing entries: "
+ svne.getMessage());
}
/*
* Gets the latest revision number of the repository
*/
long latestRevision = -1;
try {
latestRevision = repository.getLatestRevision();
} catch (SVNException svne) {
System.err.println("error while fetching the latest repository revision: "
+ svne.getMessage());
// System.exit(1);
}
System.out.println("");
System.out.println("---------------------------------------------");
System.out.println("Repository latest revision: " + latestRevision);
}
/*
* Initializes the library to work with a repository via
* different protocols.
*/
public static void listEntries(SVNRepository repository, String path)
throws SVNException {
Collection entries = repository.getDir(path, -1, null,
(Collection) null);
Iterator iterator = entries.iterator();
while (iterator.hasNext()) {
SVNDirEntry entry = (SVNDirEntry) iterator.next();
if (entry.getName().endsWith(".xml")) {
System.out.println(entry.getName() + " " + xmlfilecount);
xmlfilecount = xmlfilecount + 1;
imagefoldercheck.add(entry.getName());
}
System.out.println("imagefoldercheck --> "+imagefoldercheck);
/*
* Checking up if the entry is a directory.
*/
if (entry.getKind() == SVNNodeKind.DIR) {
listEntries(repository, (path.equals("")) ? entry.getName()
: path + "/" + entry.getName());
}
}
}
}

Java FTP file get issue

I have a application that runs as a schedule.It connect to ftp server and get files from remote folder.scheduler runs in every 5min time.Sometimes when there are lot of files in remote location, scheduler runs again while first cycle is running.In such situation some times it download 0 size files even actual file size is greater than 0 in remote location.Does anyone have any idea why this happen?
below is the code to import files.
private void importEDIFiles(String host, String user, String password, String path, String road) {
try {
String edi824Path = path + "/" + EDI_824_FOLDER;
FTPBroker ftpBroker = new FTPBroker(host, user, password, edi824Path);
FTPClient client = ftpBroker.makeFTPConeection();
String os = client.getSystemName();
client.setFileTransferMode(FTP.ASCII_FILE_TYPE);
File edi824File = null;
File edi824Filebak = null;
ArrayList<FTPFile> files;
try {
FTPFile[] ftpfiles = client.listFiles();
logger.info("\t" + ftpfiles.length + " files are in ftp location ");
if (ftpfiles.length > 0) {
files = removeZeroFiles(ftpfiles);
for(int x=0;x<files.size();x++){
logger.info("name ---"+files.get(x).getName());
logger.info("size ----"+files.get(x).getSize());
}
String ftpFile = null;
logger.info("\t" + files.size() + " downloading from " + road + " rail road.");
for (int i = 0; i < files.size(); i++) {
ftpFile = files.get(i).getName();
logger.info("\t" + ftpFile + " is downloading....");
// logger.info("\t" + ftpFile + " size ...." + ftpFile.isEmpty());
String source = destinationFilePath + pathSeparator + road + pathSeparator + ftpFile;
String target = edi_824backupFilePath + pathSeparator + road + pathSeparator + ftpFile;
edi824File = new File(source);
edi824Filebak = new File(target);
FileOutputStream fosout = new FileOutputStream(source);
boolean isRetrieved = client.retrieveFile(ftpFile, fosout);
logger.debug("isRetrieved : " + isRetrieved);
FileUtils.copyFile(edi824File,edi824Filebak);
fosout.flush();
fosout.close();
boolean isDelete = client.deleteFile(ftpFile);
logger.debug("isDelete : " + isDelete);
}
} else {
logger.info("No files to Pull in the FTP Location for " + user);
//throw new RuntimeException("No files to Pull in FTP Location.");
}
} catch (Exception e) {
logger.error(e,e);
e.printStackTrace();
} finally {
client.logout();
client.disconnect();
}
} catch (Exception ex) {
logger.error(ex, ex);
ex.printStackTrace();
}
}
you can use a flag boolean isRunning(), setRunning(boolean ), and synchronize your code so that two or more threads would not run the same method at the same time

Categories

Resources