Double File name when using FileOutputStream - java

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.

Related

Appending to text file in android

I am trying to append to a text file that starts off empty and every time the method addStudent() is called it would add a student.toString() line to the said file. I don't seem to get any exceptions but for some reason, after the method call, the file remains empty. Here is my code.
public void addStudent() {
Student student = new Student();
EditText fName = findViewById(R.id.first_name);
EditText lName = findViewById(R.id.last_name);
EditText studentGpa = findViewById(R.id.gpa);
String firstName = String.valueOf(fName.getText());
String lastName = String.valueOf(lName.getText());
String gpa = String.valueOf(studentGpa.getText());
if(firstName.matches("") || lastName.matches("") || gpa.matches("")) {
Toast.makeText(this, "Please make sure none of the fields are empty", Toast.LENGTH_SHORT).show();
} else {
double gpaValue = Double.parseDouble(gpa);
student.setFirstName(firstName);
student.setLastName(lastName);
student.setGpa(gpaValue);
try {
FileOutputStream fos = openFileOutput("students.txt", MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(student.toString());
osw.flush();
osw.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What might be the problem here? The file students.txt itself is located in assets folder
The problem may be with the fact that 'assets' directory doesnt exists on phone. So if I understand you correctly you may checking the wrong file.
What might be the problem here? The file students.txt itself is located in assets folder.
If it is in the assets folder then you should use AssetsManager top open an input stream to it. Files in the assets folder are readonly so trying to write to them does not make sense.
FileOutputStream fos = openFileOutput("students.txt", MODE_APPEND);
That wil create a file in private internal memory of your app. The code looks ok. But it makes no sense trying to find the file on your phone with a file manager or other app as as said that is private internal memory of your app only.
You use a relative path with "studends.txt" and now you do not know where the file resides.
Well the file resides in the path indicated by getFilesDir().
You could as well have used a full path with
File file = new File(getFilesDir(), "students.txt");
and then open a FileOutputStream with
FileOutputStream fos = new FileOutputStream(file);

How to make a copy of a file containing images and text using java

I have some word documents and excel sheets which has some images along with the file text content. I want to create a copy of that file and keep it at a specific location. I tried the following method which is creating file at specified location but the file is corrupted and cannot be read.
InputStream document = Thread.currentThread().getContextClassLoader().getResourceAsStream("upgradeworkbench/Resources/Upgrade_TD_Template.docx");
try {
OutputStream outStream = null;
Stage stage = new Stage();
stage.setTitle("Save");
byte[] buffer= new byte[document.available()];
document.read(buffer);
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialFileName(initialFileName);
if (flag) {
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Microsoft Excel Worksheet", "*.xls"));
} else {
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Microsoft Word Document", "*.docx"));
}
fileChooser.setTitle("Save File");
File file = fileChooser.showSaveDialog(stage);
if (file != null) {
outStream = new FileOutputStream(file);
outStream.write(buffer);
// IOUtils.copy(document, outStream);
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
Can anyone suggest me any different ways to get the proper file.
PS: I am reading the file using InputStream because it is inside the project jar.
PPS: I also tried Files.copy() but it didnt work.
I suggest you never trust on InputStream.available to know the real size of the input, because it just returns the number of bytes ready to be immediately read from the buffer. It might return a small number, but doesn't mean the file is small, but that the buffer is temporarily half-full.
The right algorithm to read an InputStream fully and write it over an OutputStream is this:
int n;
byte[] buffer=new byte[4096];
do
{
n=input.read(buffer);
if (n>0)
{
output.write(buffer, 0, n);
}
}
while (n>=0);
You can use the Files.copy() methods.
Copies all bytes from an input stream to a file. On return, the input stream will be at end of stream.
Use:
Files.copy(document, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
As the class says, the second argument is a Path, not a File.
Generally, since this is 2015, use Path and drop File; if an API still uses File, make it so that it uses it at the last possible moment and use Path all the way.

Append data in text file does not work in android application

I'm using the following code for append new position data obtained by GPS, each time position change.
if (isExternalStorageWritable()) {
if (myFile.exists()) {
try {
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(location.getLatitude()+", "+location.getLongitude()+", "+nodeCounter+"\n");
myOutWriter.close();
fOut.close();
nodeCounter++;
} catch (Exception e) {
}
} else {
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}else
{
Log.i("logGPSData","Error");
}
The problem is that the append does not work, since each time a new row is inserted, the previous row is overwritten, so my file contains always one line, even if I collect many gps data.
The second argument means if text should be appended to the existing file, change the following lines in your code:
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
to:
FileOutputStream fOut = new FileOutputStream(myFile,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut,true);
From the Docs:
public FileOutputStream(String name,boolean append)
throws FileNotFoundException
Creates a file output stream to write to the file with the specified name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection.
First, if there is a security manager, its checkWrite method is called with name as its argument.
If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.
Parameters:
1) name - the system-dependent file name
2) append - if true, then bytes will be written to the end of the file rather than the beginning
Throws:
1)FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.
2)SecurityException - if a security manager exists and its checkWrite method denies write access to the file.
Since:
JDK1.1

File renameTo does not work

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);

Java: create temp file and replace with original

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

Categories

Resources