openAssetFileDescriptor does not truncate OneDrive file - java

Using the following code, a text file that lives on Google Drive erases first as expected,leaving only the newly written content in the file. If the file lives on OneDrive the first x bytes are overwritten and the remaining original bytes left intact. Does anyone know of a work around for OneDrive files. I need the old contents erased and only the new content from the write to remain.
According to these docs
openAssetFileDescriptor and
openAssetFile
that is what should happen.
I have tried this using Java/Android Studio and C#/Xamarin, Android phone 9 api 28.
public void saveFile(View view)
{
try
{
AssetFileDescriptor pfd = getContentResolver().openAssetFileDescriptor(fileUri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(("Overwritten again " + System.currentTimeMillis() + "\n").getBytes());
fileOutputStream.close();
pfd.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}

Couldn't come up with a why it doesn't work as documented, but I have come up with a work around to simulate expected behavior. Wouldn't mind comments if anyone sees a better way.
public void saveFile(View view)
{
try
{
ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(fileUri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
//Added if-block to simulate automatic truncate when file located on onedrive.
if( (fileUri.toString()).contains("skydrive"))
{
FileChannel fileChannel = fileOutputStream.getChannel();
fileChannel.truncate(0);
}
fileOutputStream.write(("Overwritten again " + System.currentTimeMillis() + "\n").getBytes());
fileOutputStream.close();
pfd.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}

try to use following, just replace "w" with "rwt" to truncate the original file.
getContentResolver().openAssetFileDescriptor(fileUri, "rwt")

Related

File renaming always fails although the source file is closed

I am trying to rename an existing fileSrc(i.e. old_file.pdf) to another name (i.e. new_file.pdf). However the renameTo() method returns always false. I have read that its advised to check first if the original file is open (i.e. locked) and if the destination file does not exist. Here is my source code :
File fileSrc = new File("old_file.pdf");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileSrc);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} finally {
if(fos!=null)
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
File fileDst = new File("new_file.pdf");
if(fileDst.exists()) {
fileDst.delete();
}
boolean b = fileSrc.renameTo(fileDst);
System.out.println("check : "+b);//b is always set to false
P.S. I am using Windows 7 for my development environment and UNIX Debian for the production environment.

pass byte[] , file parameter to a method java

I m confused to how to pass byte array and file to a method in Java :
when I call enregistre method : enregistre(img3File, file3) and enregistre(img4File, file4) enregistre(img5File, file5) , it doesn t upload the file to the database, but when I call the part of program without method( I repeat the code with :img2File and file2 ) it worked, I dont want to repeat the code 5 times, I beleive there are a solution , help me to figure out what is wrong when I call the method please.
#RequestMapping(value="/save",method=RequestMethod.POST)
public String add (
#RequestParam("photos") MultipartFile file,
#RequestParam("photos2") MultipartFile file2,
#RequestParam("photos3") MultipartFile file3,
#RequestParam("photos4") MultipartFile file4,
#RequestParam("photos5") MultipartFile file5)
{
byte[] img1File=null;
try {
//////////////////////// part1
img1File= file.getBytes();
BufferedOutputStream stream;
stream = new BufferedOutputStream(new FileOutputStream(new File("ben1")));
stream.write(img1File);
stream.close();
//////////////////// end part 1
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// here I repeat the code and I don t want to repeat it
byte[] img2File=null;
try {
//////////////////////// part 2
img2File= file2.getBytes();
BufferedOutputStream stream;
stream = new BufferedOutputStream(new FileOutputStream(new File("ben1")));
stream.write(img2File);
stream.close();
////////////////////////end part 2
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] img3File=null;
enregistre(img3File, file3);
byte[] img4File=null;
enregistre(img4File, file4);
byte[] img5File=null;
enregistre(img5File, file5);
Annonce annonce=new Annonce();
annonce.setPhotos(img1File);
annonce.setPhotos2(img2File);
annonce.setPhotos3(img3File);
annonce.setPhotos4(img4File);
annonce.setPhotos5(img5File);
annoncedao.save(annonce);
return "SuccessAddAnnonce";
// method
public void enregistre(byte[] imgFile,MultipartFile file)
{
try {
imgFile= file.getBytes();
BufferedOutputStream stream;
stream = new BufferedOutputStream(new FileOutputStream(new File("ben1")));
stream.write(imgFile);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Look at what your enregistre method does:
BufferedOutputStream stream;
stream = new BufferedOutputStream(new FileOutputStream(new File("ben1")));
stream.write(imgFile);
stream.close();
If you call that method multiple times, it will write to the same file multiple times. There's no point in that - you'll just end up with the file containing the data for the last call. Note that the method doesn't do anything with a database - it just writes a file. You haven't explained to us where the code that does write to the database is, but presumably it's reading from that file at some point.
(Aside from that, the first parameter of the method is completely useless, as you immediately reassign it. This code has some serious issues in terms of code hygiene, but I've focused just on what you were asking.)

Contents not being written to file using Java [duplicate]

This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
I am trying to get input from a JOptionPane and store what the user typed into a text file using the FileWriter class.To make sure that the input from what the user typed was being stored I wrote a system.out and what I typed in the JOptionPane appears. Unfortunately when I open the .txt file nothing I entered appears! By the way, the file path I entered is correct.
Here is my code. HELP ME!
String playername = JOptionPane.showInputDialog("What Will Be Your Character's Name?");
System.out.println(playername);
try {
FileWriter charectersname = new FileWriter("/Users/AlecStanton/Desktop/name.txt/");
BufferedWriter out = new BufferedWriter(charectersname);
out.write(playername);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Buffered writers will only write out when they're full or when they're being closed (hence the name Buffered).
So you can do this:
out.close();
which will flush the buffer and then close it. If you only wanted to flush it but keep it open for further writes (e.g. imagine you're writing a log file), you could do:
out.flush();
You'd likely want to do this when finishing up with such a resource. e.g.
BufferedWriter out = ...
try {
out.write(...);
}
catch (Exception e) {
// ..
}
finally {
out.close();
}
Or possibly using the try-with-resources constructs in Java 7, which (frankly) is more reliable to write code around.
The Java 7 version with the try() closing automatically.
try (BufferedWriter out = new BufferedWriter(
new FileWriter("/Users/AlecStanton/Desktop/name.txt"))) {
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
}
Mind the left-out / after .txt.
You should close your writer in a finally block.
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("/Users/AlecStanton/Desktop/name.txt/"));
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null){
out.close();
} else {
System.out.println("Buffer has not been initialized!");
}
} catch (IOException e) {
e.printStackTrace();
}
}

FileWriter in java not writing to txt file [duplicate]

This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
I am trying to get input from a JOptionPane and store what the user typed into a text file using the FileWriter class.To make sure that the input from what the user typed was being stored I wrote a system.out and what I typed in the JOptionPane appears. Unfortunately when I open the .txt file nothing I entered appears! By the way, the file path I entered is correct.
Here is my code. HELP ME!
String playername = JOptionPane.showInputDialog("What Will Be Your Character's Name?");
System.out.println(playername);
try {
FileWriter charectersname = new FileWriter("/Users/AlecStanton/Desktop/name.txt/");
BufferedWriter out = new BufferedWriter(charectersname);
out.write(playername);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Buffered writers will only write out when they're full or when they're being closed (hence the name Buffered).
So you can do this:
out.close();
which will flush the buffer and then close it. If you only wanted to flush it but keep it open for further writes (e.g. imagine you're writing a log file), you could do:
out.flush();
You'd likely want to do this when finishing up with such a resource. e.g.
BufferedWriter out = ...
try {
out.write(...);
}
catch (Exception e) {
// ..
}
finally {
out.close();
}
Or possibly using the try-with-resources constructs in Java 7, which (frankly) is more reliable to write code around.
The Java 7 version with the try() closing automatically.
try (BufferedWriter out = new BufferedWriter(
new FileWriter("/Users/AlecStanton/Desktop/name.txt"))) {
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
}
Mind the left-out / after .txt.
You should close your writer in a finally block.
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("/Users/AlecStanton/Desktop/name.txt/"));
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null){
out.close();
} else {
System.out.println("Buffer has not been initialized!");
}
} catch (IOException e) {
e.printStackTrace();
}
}

save a file in java

I am trying to save a file in Java in this way:
PrintWriter output = null;
int x=5, y = 6;
try {
saveFile = new FileOutputStream("myFile.txt");
save = new ObjectOutputStream(saveFile);
save.writeObject(x + y);
save.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
and it is working but how can I save an object from another class because it is giving me an error when I try to do it.
Like the others say, plenty of things that might be problematic ... However serialization is one way to store a object in a file and read it back to a object from a file.
http://www.java-samples.com/showtutorial.php?tutorialid=398

Categories