I am currently working on a Project and would like to save an object to a file with ObjectOutputStream to a location the user chooses with the help of a JFileChooser. But the object is always saved to the root directory of the program into the file named "null" (%ProjectDirectory%/null).
Here's my method saveObjects, which saves a LinkedList of objects to a file:
public void saveObjects(String filePath) {
try {
FileOutputStream os = new FileOutputStream(filePath);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(oceanObjects);
oos.close();
os.close();
} catch(IOException e) {
System.err.println(e);
}
}
This instruction calls the method saveObject with the filepath as a parameter (filePath is a String; I already tried to use a File)
saveObjects(view.getFilePath());
view is an instance of OceanLifeView and view.getFilePath() is a getter-method of that class that returns the path where the file should be saved (as a String).
getFilePath() looks like this:
public String getFilePath() {
return filePath;
}
And my OceanLifeView like this:
OceanLifeView(String title, int type) {
if(...) {
...
}else if (title.equals("fileChooser")) {
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(FILES_ONLY);
if (type == 0) {
//Load Button functions
System.out.println("De-Serialisation started fileChooserGUI!");
returnVal = fileChooser.showOpenDialog(fileChooser);
} else {
//Save Button functions
System.out.println("Serialisation started fileChooserGUI!");
returnVal = fileChooser.showSaveDialog(fileChooser);
}
if (returnVal == JFileChooser.APPROVE_OPTION) {
filePath = fileChooser.getSelectedFile();
}
}
}
I would be very thankful to anybody who can share some insight for the problem I encounter or mistake I made implementing this functionality.
This looks as if you are passing files relative path to FileOutputStream constructor.
Probable cause of that is that filePath is calculated as filePath = selectedFile.getPath() instead it should be calculated like this:
File selectedFile = fileChooser.getSelectedFile();
String filePath = selectedFile.getAbsolutePath();
Related
I have a camera that I am grabbing values pixel-wise and I'd like to write them to a text file. The newest updates for Android 12 requires me to use storage access framework, but the problem is that it isn't dynamic and I need to keep choosing files directory. So, this approach it succesfully creates my files but when writting to it, I need to specifically select the dir it'll save to, which isn't feasible to me, as the temperature is grabbed for every frame and every pixel. My temperature values are in the temperature1 array, I'd like to know how can I add consistently add the values of temperature1 to a text file?
EDIT: I tried doing the following to create a text file using getExternalFilesDir():
private String filename = "myFile.txt";
private String filepath = "myFileDir";
public void onClick(final View view) {
switch (view.getId()){
case R.id.camera_button:
synchronized (mSync) {
if (isTemp) {
tempTureing();
fileContent = "Hello, I am a saved text inside a text file!";
if(!fileContent.equals("")){
File myExternalFile = new File(getExternalFilesDir(filepath), filename);
FileOutputStream fos = null;
try{
fos = new FileOutputStream(myExternalFile);
fos.write(fileContent.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
Log.e("TAG", "file: "+myExternalFile);
}
isTemp = false;
//Log.e(TAG, "isCorrect:" + mUVCCamera.isCorrect());
} else {
stopTemp();
isTemp = true;
}
}
break;
I can actually go all the way to the path /storage/emulated/0/Android/data/com.MyApp.app/files/myFileDir/ but strangely there is no such file as myFile.txt inside this directory, how come??
Working Solution:
public void WriteToFile(String fileName, String content){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File newDir = new File(path + "/" + fileName);
try{
if (!newDir.exists()) {
newDir.mkdir();
}
FileOutputStream writer = new FileOutputStream(new File(path, filename));
writer.write(content.getBytes());
writer.close();
Log.e("TAG", "Wrote to file: "+fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
I'm saving images to my resources folder regardless of the extension, and I want to load them the same way. Example: I want to get the image named "foo" whether it is "foo.jpg" or "foo.png".
Right now I'm loading the image for each extension and returning it if it exists OR trying for the next extension if an exception is thrown like so:
StringBuilder relativePath = new StringBuilder().append("src/main/resources/static/images/").append("/")
.append(id).append("/").append(imageName);
File imageFile = null;
byte[] imageBytes = null;
try {
imageFile = new File(new StringBuilder(relativePath).append(".jpg").toString());
imageBytes = Files.readAllBytes(imageFile.toPath());
} catch (IOException e) {
}
if (imageBytes == null) {
imageFile = new File(relativePath.append(".png").toString());
imageBytes = Files.readAllBytes(imageFile.toPath());
}
I feel like it's not the best way to do that, is there a way to load an image by its name and regardless of the extension?
You need to check it the file exists
File foo = new File("foo.jpg");
if (!foo.exists) {
foo = new File("foo.png");
}
But if you really want to load without using the extension, then you could list the files in directory that match a given pattern.
File dir = new File("/path/to/images/dir/");
File [] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.matches("foo\\.(jpg|png)");
}
});
File foo = files[0];
I searched around but couldn't find nothing on this.
I would like to set the save (destination) path for a file selected in Filechooser. For example, I selected a picture called 'test.jpg', I would like for this 'test.jpg' to be saved to C:\blah\blah\blah\Pictures. How can I pull this off?
So far the code I have
public void OnImageAddBeer(ActionEvent event){
FileChooser fc = new FileChooser();
//Set extension filter
fc.getExtensionFilters().addAll(new ExtensionFilter("JPEG Files (*.jpg)", "*.jpg"));
File selectedFile = fc.showOpenDialog(null);
if( selectedFile != null){
}
}
All you need to do is copy the content inside the file choose in wherever you want, try something like this:
if(selectedFile != null){
copy(selectedFile.getAbsolutePath(), "C:\\blah\\blah\\blah\\Pictures\\test.jpg");
}
and the method copy:
public void copy(String from, String to) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(from);
fw = new FileWriter(to);
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
//...
}
}
Basically copy just copy the content of the file located in from inside a new file located at to.
Try this:
String fileName = selectedFile.getName();
Path target = Paths.get("c:/user/test", fileName);
Files.copy(selectedFile.toPath(), target);
Add this statement if you want to set the destination path:
fc.setInitialDirectory(new File(System.getProperty("user.home") + "\\Pictures"));
Take this:
String dir = System.getProperty("user.dir");
File f = new File(dir + "/abc/def");
fc.setInitialDirectory(f);
I am using JDK 6.
I have 2 folders names are Folder1 and Folder2.
Folder1 have the following files
TherMap.txt
TherMap1.txt
TherMap2.txt
every time Folder2 have only one file with name as TherMap.txt.
What I want,
copy any file from folder1 and pasted in Folder2 with name as TherMap.txt.If already TherMap.txt exists in Folder2, then delete and paste it.
for I wrote the following code.but it's not working
public void FileMoving(String sourceFilePath, String destinationPath, String fileName) throws IOException {
File destinationPathObject = new File(destinationPath);
File sourceFilePathObject = new File(sourceFilePath);
if ((destinationPathObject.isDirectory()) && (sourceFilePathObject.isFile()))
//both source and destination paths are available
{
//creating object for File class
File statusFileNameObject = new File(destinationPath + "/" + fileName);
if (statusFileNameObject.isFile())
//Already file is exists in Destination path
{
//deleted File
statusFileNameObject.delete();
//paste file from source to Destination path with fileName as value of fileName argument
FileUtils.copyFile(sourceFilePathObject, statusFileNameObject);
}
//File is not exists in Destination path.
{
//paste file from source to Destination path with fileName as value of fileName argument
FileUtils.copyFile(sourceFilePathObject, statusFileNameObject);
}
}
}
I call the above function in main()
//ExternalFileExecutionsObject is class object
ExternalFileExecutionsObject.FileMoving(
"C:/Documents and Settings/mahesh/Desktop/InputFiles/TMapInput1.txt",
"C:/Documents and Settings/mahesh/Desktop/Rods",
"TMapInput.txt");
While I am using FileUtils function, it showing error so I click on error, automatically new package was generated with the following code.
package org.apache.commons.io;
import java.io.File;
public class FileUtils {
public static void copyFile(File sourceFilePathObject,
File statusFileNameObject) {
// TODO Auto-generated method stub
}
}
my code not showing any errors,even it's not working.
How can I fix this.
Thanks
Use Apache Commons FileUtils
FileUtils.copyDirectory(source, desc);
Your code isn't working because in order to use the ApacheCommons solution you will have to download the ApacheCommons library found here:
http://commons.apache.org/
and add a reference to it.
Since you are using JRE 6 you can't use all the NIO file utilities, and despite everyone loving Apache Commons as a quick way to answer forum posts, you may not like the idea of having to add that utility on just to get one function. You can also use this code that uses a transferFrom method without using ApacheCommons.
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
}
FileInputStream fIn = null;
FileOutputStream fOut = null;
FileChannel source = null;
FileChannel destination = null;
try {
fIn = new FileInputStream(sourceFile);
source = fIn.getChannel();
fOut = new FileOutputStream(destFile);
destination = fOut.getChannel();
long transfered = 0;
long bytes = source.size();
while (transfered < bytes) {
transfered += destination.transferFrom(source, 0, source.size());
destination.position(transfered);
}
} finally {
if (source != null) {
source.close();
} else if (fIn != null) {
fIn.close();
}
if (destination != null) {
destination.close();
} else if (fOut != null) {
fOut.close();
}
}
}
When you upgrade to 7, you will be able to do the following
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
reference:
https://gist.github.com/mrenouf/889747
Standard concise way to copy a file in Java?
What im trying to do is simply letting the user choose a directory to save a text file to, Problem is im trying to select a folder im creating on my desktop but when i select the folder with the JFileChooser and letting the code i have do the work it's still saved outside the folder and into the desktop.. Why? Can someone please explain what i did wrong so i might learn something..
public class TextFileSaver {
String filePath;//Used in the setPath and getPath methods
String filename = File.separator+"tmp"; //Used for the JFileChoosers directory
public TextFileSaver(){
//Get our file saver to the screen
JFileChooser fc = new JFileChooser(new File(filename));
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //Only able to select directiories
// Show open dialog; this method does not return until the dialog is closed
fc.showSaveDialog(null);
File selectedLocation = fc.getCurrentDirectory(); //Gets the selected Location
//Sets the path of the file so we can read from it.
setPath(selectedLocation.getAbsolutePath());
FileName();
try {
SaveFile(filePath);
}
catch (IOException ex) {
Logger.getLogger(TextFileSaver.class.getName()).log(Level.SEVERE, null, ex);
//Show a message dialog
JOptionPane.showMessageDialog(null, "The file could not be saved, Please try again.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public void setPath(String Path){
filePath = Path;
}
public String getPath(){
return filePath;
}
private void FileName(){
String name = JOptionPane.showInputDialog
("What name do you want to give the file?");
//Temporary code bellow will change to StringBuilder here.
filePath = filePath + "/" + name + ".txt";
}
private void SaveFile(String Path) throws IOException{
System.out.println(Path);
//The outStream that we will use to write to the text file the user is creating.
PrintWriter outStream = new PrintWriter(new BufferedWriter(new FileWriter(Path)));
outStream.println("Test text!");
outStream.close();
}
}
All the methods are executed through the constructor.. So the code happends step by step..
Use getSelectedFile() and not getCurrentDirectory() and also, you should append your filePath somewhere.