I am trying to add an extension to the name of file selected by a JFileChooser although I can't get it to work.
This is the code :
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
String name =f.getAbsoluteFile()+".txt";
f.renameTo(new File(name));
FileWriter fstream;
try {
fstream = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fstream);
out.write("test one");
out.close();
} catch (IOException ex) {
Logger.getLogger(AppCore.class.getName()).log(Level.SEVERE, null, ex);
}
}
I can't figure out why this doesn't work. I also tried using getPath() and getCanonicalPath() but the result is the same. The file is created at the directory selected, although without a ".txt" extension.
It seems to me that all you want to do is to change the name of the file chosen, as opposed to renaming a file on the filesystem. In that case, you don't use File.renameTo. You just change the File. Something like the following should work:
File f = fc.getSelectedFile();
String name = f.getAbsoluteFile()+".txt";
f = new File(name);
File.renameTo attempts to rename a file on the filesystem. For example:
File oldFile = new File("test1.txt");
File newFile = new File("test2.txt");
boolean success = oldFile.renameTo(newFile); // renames test1.txt to test2.txt
After these three lines, success will be true if the file test1.txt could be renamed to test2.txt, and false if the rename was unsuccessful (e.g. test1.txt doesn't exist, is open in another process, permission was denied, etc.)
I will hazard a guess that the renaming you are attempting is failing because you are attempting to rename a directory (you are using a JFileChooser with the DIRECTORIES_ONLY option). If you have programs using files within this directory, or a Command Prompt open inside it, they will object to this directory being renamed.
You could also use the Files.move utility from Google Guava libraries to rename a file. Its easier than writing your own method.
From the docs:
Moves the file from one path to another. This method can rename a file or move it to a different directory, like the Unix mv command.
You are writing to the wrong file. When you call renameTo, the current file doesn't change it's path. Try this:
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
String name =f.getAbsoluteFile()+".txt";
File f2 = new File(name);
f.renameTo(f2);
FileWriter fstream;
try {
fstream = new FileWriter(f2);
BufferedWriter out = new BufferedWriter(fstream);
out.write("test one");
out.close();
} catch (IOException ex) {
Logger.getLogger(AppCore.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to Rename the file then there is must to close all the object (like FileReader,FileWriter ,FIS ,FOSmeans close the the reading file object and then rename it
You need to create a new instance to refer to the new name of the file
oldFile = new File(newName);
Related
I'm trying to save a file using this code:
//file save first time
JFileChooser chooser = new JFileChooser();
//set name for default file for the file chooser.
chooser.setSelectedFile(new File(communicator.getFileName()));
int retrival = chooser.showSaveDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try {
//write log message to textfield
communicator.writeToField("[Save File]: Saving file at: " + chooser.getSelectedFile().getAbsolutePath());
//setup output stream
FileOutputStream fos = new FileOutputStream(new File(chooser.getSelectedFile().getAbsolutePath()+".bin"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
//get the object to serialize
oos.writeObject(communicator.getCurrentFileObject());
} catch (Exception ex) {
ex.printStackTrace();
}
} else
//write log message to textfield
communicator.writeToField("[Save File]: Operation aborted by user...");
when I use this the output of the code is [Save File]: Saving file at: /home/name/documents/test.bin
but whenever I go and look at the actuall file inside the folder it's name is testtest.bin. so the name gets repeated twice. What can be the problem here?
When
chooser.getSelectedFile().getAbsolutePath()
already delivers the output
/home/name/documents/test.bin
as your logging shows. Why do you then add another ".bin"?
new File(chooser.getSelectedFile().getAbsolutePath()+".bin")
I reckon the additional ".bin" causes your problem. Just leave it out. You don't need it as your logging shows.
In my program, I want to sent some files from client to server using socket programming. I'm using the void setMultiSelectionEnabled(boolean b) method so I can choose more than 1 file, but it gives me an error when i try to get the path of the file. Here's my code:
JFileChooser choose = new JFileChooser();
choose.setAcceptAllFileFilterUsed(false);
choose.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "jpeg"));
choose.setAcceptAllFileFilterUsed(true);
choose.setMultiSelectionEnabled(true);
File[] f = choose.getSelectedFiles();
choose.showOpenDialog(this);
String filePath = f.getAbsolutePath();
String fname = f.getName();
Client_ftp cli = new Client_ftp();
if(cli.kirim(filePath, fname)) {
jLabel1.setText("Success. .");
} else {
jLabel1.setText("failed");
}
f is an array. You'll need to index the array before calling the getAbsolutePath() method for each File in f. Make sure to check for null prior to doing so.
Example: f[0].getAbsolutePath();
When I create a file in java servlet, I can't find that file for opening. This is my code in servlet:
FileOutputStream fout;
try {
fout = new FileOutputStream("title.txt");
new PrintStream(fout).println(request.getParameter("txttitle"));
fout.close();
System.out.println(request.getParameter("txttitle"));
} catch (Exception e) {
System.out.println("I can't create file!");
}
Where I can find that file?
if you create file first as in
File f = new File("title.txt");
fout = new FileOutputStream(f);
then you use getAbsolutePath to return the location of where it has been created
System.out.println (f.getAbsolutePath());
Since you have'nt specified any directory for the file, it will be placed in the default directory of the process that runs your servlet container.
I would recommand you to always specify the full path of your your file when doing this kind of things.
If you're running tomcat, you can use System.getProperty("catalina.base") to get the path of the tomcat base directory. This can sometimes help.
Create a file object and make sure the file exists:-
File f = new File("title.txt");
if(f.exists() && !f.isDirectory()) {
fout = new FileOutputStream(f);
new PrintStream(fout).println(request.getParameter("txttitle"));
fout.close();
System.out.println(request.getParameter("txttitle"));
}
If the servlet cannot find the file give the full path to the file specified, like new File("D:\\Newfolder\\title.txt");
you should check first if the file doesn't exist ,create it
if(!new File("title.txt").exists())
{
File myfile = new File("title.txt");
myfile.createNewFile();
}
then you can use FileWriter or FileOutputStream to write to the file i prefer FileWriter
FileWriter writer = new FileWriter("title.txt");
writer.write("No God But Allah");
writer.close();
simply simple
The following code writes a string to a specific file.
String content = "Text To be written on a File";
File file = new File("c:/file.txt");
FileOutputStream foutput = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] c = content.getBytes();
foutput.write(c);
foutput.flush();
foutput.close();
I want to use this code in a Jbutton so every time the user clicks it, it writes the string to a NEW text file NOT OVERWRITE the existed one. I tried to do but I couldn't get the result.
Thank you in advance.
There's a couple of different ways you can get this result, it really depends on the application. The two easiest ways to do this would to be either:
Append the current timestamp to the file name
Use the File API to create a "temp file" in the directory, which is guarenteed to have a unique name
Option 1:
String baseDir = "c:/";
File newFile = new File(baseDir, "file_" + System.currentTimeMillis() + ".txt");
// do file IO logic here...
Option 2:
String baseDir = "c:/";
File newFile = File.createTempFile("file", ".txt", new File(baseDir));
// do file IO logic here...
If you want to write it to a new file, you have to create a new file. The name of the text file is always file.txt in your case.
Try this:
private int filecounter = 0; // this is the member of your class. Outside the function.
//inside your function
File file = new File("c:/file" + Integer.(filecounter).toString() + ".txt");
// you do something here.
filecounter++;
This way, your files will be stored as file0.txt, file1.txt etc.
i need some help with creating file
Im trying in the last hours to work with RandomAccessFile and try to achieve the next logic:
getting a file object
creating a temporary file with similar name (how do i make sure the temp file will be created in same place as the given original one?)
write to this file
replace the original file on the disk with the temporary one (should be in original filename).
I look for a simple code who does that preferring with RandomAccessFile
I just don't how to solve these few steps right..
edited:
Okay so ive attachted this part of code
my problem is that i can't understand what should be the right steps..
the file isn't being created and i don't know how to do that "switch"
File tempFile = null;
String[] fileArray = null;
RandomAccessFile rafTemp = null;
try {
fileArray = FileTools.splitFileNameAndExtension(this.file);
tempFile = File.createTempFile(fileArray[0], "." + fileArray[1],
this.file); // also tried in the 3rd parameter this.file.getParentFile() still not working.
rafTemp = new RandomAccessFile(tempFile, "rw");
rafTemp.writeBytes("temp file content");
tempFile.renameTo(this.file);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
rafTemp.close();
}
try {
// Create temp file.
File temp = File.createTempFile("TempFileName", ".tmp", new File("/"));
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("Some temp file content");
out.close();
// Original file
File orig = new File("/orig.txt");
// Copy the contents from temp to original file
FileChannel src = new FileInputStream(temp).getChannel();
FileChannel dest = new FileOutputStream(orig).getChannel();
dest.transferFrom(src, 0, src.size());
} catch (IOException e) { // Handle exceptions here}
you can direct overwrite file. or do following
create file in same directory with diff name
delete old file
rename new file