Alternative ways to rename a flat file in Java - java

So im writing a program that reads a txt file that the user provides the name of from a specific folder
I want to rename the .txt after the user has opened it. However, nothing happens
temp = userInput;
currentFileDir = "D:\\Document\\" + username + "\\" + temp1 ;
File directory = new File(currentFileDir + ".txt");
Scanner readingFile = new Scanner(directory);
while (readingFile.hasNextLine())
{
txtdata = txtdata + readingFile.nextLine() + " ";
}
File newName = new File(currentFileDir + "--OPENED.txt");
directory.renameTo(newName);
System.out.println(txtdata);
}
Is there something wrong with the code I provided?
I've tried using it in a standalone program and it works fine, so I think that the rest of the code of my program must interfere with the rename process.
Are there any alternatives to "renameTo"?

Related

How can I solve the error of the "no such a directory or file"?

I have this simple code, but when I run, I get an error of not such a directory or file! how can I solved I tried many ways none of them works!! can anyone help?
public static void main (String [] args) {
String songA = ("res/raw/canon_d_major.wav");
String songB = ("res/raw/canon_d_major.wav");
Wave waveA = new Wave(songA);
Wave waveB = new Wave(songB);
String recordedClip = ("res/raw/cock_a.1.wav");
Wave waveRec = new Wave(recordedClip);
FingerprintSimilarity similarity1, similarity2;
similarity1= waveA.getFingerprintSimilarity(waveRec);
System.out.println("clip is found at " +
similarity.getsetMostSimilarTimePosition() + "s in " + songA +
" with similarity " + similarity.getSimilarity());
similarity2 = waveB.getFingerprintSimilarity(waveRec);
System.out.println("clip is found at " +
similarity.getsetMostSimilarTimePosition() + "s in " + songB +
" with similarity " + similarity.getSimilarity());
}
File fileName = new File('path/to/file'); does not create file on your hdd. Its only new File object in java that points to the dir you set in constructor. With that said if cock_a.wav doesnt exist while code is executing it wont be physically created.
Use this -> Java's createNewFile() - will it also create directories?
Also it might be helpful if you post your directory structure here.

Importing .sql file into MySQL using Java code

I'm trying to programmatically import a .sql file into MySQL. The .sql file was generated by mysqldump. I'm trying to do this dynamically in a Java program. But, it keeps failing on the "<" character within Java (I think). If I grab the String in the debugger of the command it's about to run (the "combined" variable below), and paste it into the command line, it works fine. Likewise, when I was trying to get the mysqldump working inside this program, it failed on the ">" character, and I had to replace it with the "--result-file=" argument to get it to work.
String command = mySqlPath + "mysql.exe";
String user = "-u " + settings.dbUser;
String password = "-p" + settings.dbPassword;
String db = settings.dbDatabase;
String inputFile = filePath + mySqlDumpFile;
String combined = command + " " + user + " " + password + " " + db + " < " + inputFile;
ExternalCommandExecuter ece = new ExternalCommandExecuter(combined);
int code = ece.execute();
This results in this String for example
C:\software\mysql5\bin\mysql.exe -u root -p<password>
db_name < C:\software\tomcat7\webapps\ROOT\WEB-INF\documents\dump-1461789460425.sql
Which will result in a exitCode of 1. Pasting it into the command line, and it'll work.
So I couldn't get it to work in Java by importing the file with a "<", instead I had to write an external .sh/.bat file which I call from my Java code.

Rename file in JFileChooser if file exists and user inputs extension

The code works as it has to until user inputs a filename with extension (.txt) and it already exists. So if the file "test.txt" exists and the user decides to name the new file as "test", it will be named as "test(1).txt", but if the user adds extension like "test.txt", the file will be named as "test.txt" and the next file user names "test.txt" will be saved as "test.txt(1).txt".
Is it possible to get the name of file from JFileChooser, remove it's extension if user input it and use it as name of the new file after adding number in the middle of original file name and it's extension? I can get name without extension as String type, but I need it as File type.
File ft = fc.getSelectedFile();
String ext = ".txt";
File tmp = new File(ft.getPath());
if (!fc.getSelectedFile().getAbsolutePath().endsWith(ext)){
ft = new File (ft + ext);
}
File test = new File(ft.getPath());
File temp = new File(ft.getPath());
File temp1 = new File(ft.getPath());
int count = 1;
while (temp.exists()) {
if(tmp.getAbsolutePath().endsWith(ext)){
}
File ft1 = new File (tmp + "(" + count + ")");
ft = new File (tmp + "(" + count + ")" + ext);
count++;
temp = new File(ft.getPath());
temp1 = new File(ft1.getPath());
}
if (!temp1.getAbsolutePath().endsWith(ext)){
ft = new File (temp1 + ext);
}
int cnt = count - 1;
if (!test.equals(temp)){
JOptionPane.showMessageDialog(null, "File already exists. So it's saved with (" + cnt + ") at the end.");
}
OK so I've tried to make this work without changing your code too much. Try this:
String filePath = fc.getSelectedFile().getAbsolutePath();
final String ext = ".txt";
String filePathWithoutExt;
if (filePath.endsWith(ext)) {
filePathWithoutExt = filePath.substring(0, filePath.length() - ext.length());
} else {
filePathWithoutExt = filePath;
}
File test = new File(filePathWithoutExt + ext);
File temp = new File(filePathWithoutExt + ext);
int count = 0;
while (temp.exists()) {
count++;
temp = new File(filePathWithoutExt + "(" + count + ")" + ext);
}
if (!test.equals(temp)) {
JOptionPane.showMessageDialog(null,
"File already exists. So it's saved with (" + count + ") at the end.");
}
EDIT:
By the recommendation of Marco N. it could be better to determine whether or not an extension exists by finding the last position of the . since this would also work with extensions other than ".txt". This value would then be used to split the string. The replacement code would look like this:
final int lastPeriodPos = filePath.lastIndexOf(".");
if (lastPeriodPos >= 0) {
filePathWithoutExt = filePath.substring(0, lastPeriodPos);
} else {
filePathWithoutExt = filePath;
However this would also have some issues if the user entered a file name that contained the . anywhere other than just before the file extension.
Hmm, I think this entry might be useful as well:
Remove filename extension in Java
I currently lack the time to properly test it (or better test it at all) but shouldn't it work this way:
public static String removeExtention(File f) {
String name = f.getName();
// Now we know it's a file - don't need to do any special hidden
// checking or contains() checking because of:
final int lastPeriodPos = name.lastIndexOf('.');
if (lastPeriodPos <= 0)
{
// No period after first character - return name as it was passed in
return f;
}
else
{
// Remove the last period and everything after it
File renamed = new File(f.getParent(), name.substring(0, lastPeriodPos));
return renamed;
}
}
I briefly tried to adjust the code from the posting mentioned above and it may very well contain some errors or flaws. (If you find some, do not hesitate to comment on them. Some of them might be due to my current lack of time, but I am always willing to learn and improve.) However I hope this may help you to find a proper solution to your problem.

Trying to get file paths to work across all releases in Java/Netbeans

So I'm working on a game, and I need help with my file i/o for savefiles. Currently I have something like this setup to read from them:
public static void savesManagementMenu() {
for (int i = 1; i < 4; i++) {
fileURL = JRPG.class.getResource("Saves/save" + i + ".txt");
System.out.println(fileURL);
if (fileURL != null) {
saveMenuSaveFile = new File(fileURL.getPath());
try {
//System.out.println("File # " + i +" exists.");
saveMenuSaveFileReader = new FileReader(fileURL.getPath());
saveMenuFileScanner = new Scanner(saveMenuSaveFileReader);
saveMenuInfo[i - 1][0] = saveMenuFileScanner.nextLine();
saveMenuFileScanner.nextLine();
saveMenuFileScanner.nextLine();
saveMenuFileScanner.nextLine();
saveMenuInfo[i - 1][1] = saveMenuFileScanner.nextLine();
saveMenuInfo[i - 1][2] = saveMenuFileScanner.nextLine();
} catch (FileNotFoundException ex) {
Logger.getLogger(JRPG.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
saveMenuInfo[i - 1][0] = null;
}
}...
And running/compiling using this method from Netbeans will make the application/game look in "E:\Copy\JRPG\build\classes\jrpg\Saves."
When I clean and build the project, and try to run it via the command line I get a response like this:
jar:file:/C:/Users/Adam/Desktop/New%20folder/JRPG.jar!/jrpg/Saves/save1.txt
Aug 22, 2013 11:54:18 PM jrpg.JRPG savesManagementMenu
SEVERE: null
java.io.FileNotFoundException: file:\C:\Users\Adam\Desktop\New%20folder\JRPG.jar
!\jrpg\Saves\save1.txt (The filename, directory name, or volume label syntax is
incorrect)
And the game just freezes up. The file path for the saves that I want it to look into when I run the compiled code is: C:\Users\Adam\Desktop\New folder\Saves
Which would be the relative file path right? How can I fix this problem so that my compiled code looks in the correct location no matter where I run the file from? (Lets say my friend wanted to run the game from his computer except he put the "New Folder" folder somwhere other than his desktop)
A embedded resource is not a File and can't be treated as one. Also, as far as output files, you shouldn't be trying to save inside your application anyway...
Instead, either save the file to the relative location of your application...
File saveMenuSaveFile = new File("./Saves/save" + i + ".txt");
Or to the users home directory...
String userHome = System.getProperty("user.home");
File saveMenuSaveFile = new File(userHome + "/.YouApplicationName/Saves/save" + i + ".txt");

Generate filename for a copied file

I am looking to get similar behaviour to what you get in Windows when you copy and paste a file in the same directory.
For e.g, if you've copy/paste a file called foo.txt, it will create foo Copy.txt and if you paste it once more, it creates foo Copy(2).txt and if you copy/paste foo Copy.txt, foo Copy Copy.txt is created.
Is there a Java utility function that does this? I've looked at File.createTempFile but the filename it generates is too long and contains a UID-like substring.
By using the FileChooser in combination with the "showSaveDialog"-method you will get the result you want, because java is then using the OS behaviour for existing files.
Sometimes, you just have to do the work first, it will give you an appreciation for the API. Then you can write your own utility methods
File original = new File("build.xml");
String path = original.getAbsoluteFile().getParent();
String name = original.getName();
String ext = name.substring(name.indexOf("."));
name = name.substring(0, name.indexOf("."));
name = path + File.separator + name;
int index = 1;
File copy = new File(name + " (" + index + ")" + ext);
while (copy.exists()) {
index++;
copy = new File(name + " (" + index + ")" + ext);
}
System.out.println(copy);

Categories

Resources