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.)
Related
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")
I've read this Reading a resource file from within jar however I couldn't figure out how to get a file instead of a inputstream, which is what I need. This is the code:
private void duplicateDocument() {
FileOutputStream fos = null;
File file;
try {
try {
doc = new File(getClass().getResource("1.docx").toURI());
//doc = new File(getClass().getResourceAsStream("1.docx"));
} catch (URISyntaxException ex) {
Logger.getLogger(ForensicExpertWitnessReportConfigPanel.class.getName()).log(Level.SEVERE, "Failed ...", ex);
}
file = new File("C:\\Users\\student\\Documents\\myfile.docx");
fos = new FileOutputStream(file);
/* This logic will check whether the file
* exists or not. If the file is not found
* at the specified location it would create
* a new file
*/
if (!file.exists()) {
file.createNewFile();
}
/*String content cannot be directly written into
* a file. It needs to be converted into bytes
*/
byte[] bytesArray = FileUtils.readFileToByteArray(doc);
fos.write(bytesArray);
fos.flush();
System.out.println("File Written Successfully");
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {
if (fos != null)
{
fos.close();
}
}
catch (IOException ioe) {
System.out.println("Error in closing the Stream");
}
}
}
FileUtils.readFileToByteArray is the only thing I've been able to get working so far, which is why I need the value a a file rather than an inputstream.
Currently, the code above gives "A java.lang.IllegalArgumentException" which is why I saw a suggestion online to use getResourceAsStream() instead - however haven't been able to return it as a file.
My next option is to try Reading a resource file from within jar - buffered reader instead.
Can someone help?
I recommend Files with its many useful functions:
Path out = Paths.get("C:\\Users\\student\\Documents\\myfile.docx");
InputStream in = getClass().getResourceAsStream("1.docx");
Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
A resource in principle is a read-only file, possibly zipped in a jar.
Hence one cannot write back to it, and it can only serve as template for a real file, as is done here.
I got it working, using this:
InputStream in = getClass().getResourceAsStream("1.docx");
byte[] bytesArray = IOUtils.toByteArray(in);
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();
}
}
I'm trying to write a few helper methods to take care of reading and writing an encrypted file. I have two methods which successfully fulfill this and return an InputStream or an OutputStream (which are really the Cipher version) that I can use to read or write to the file. I have confirmed that these methods work peachy keen when wrapped with an Object stream and used to read and write an encrypted Object to file.
However, the problem arises when I try to read from an encrypted text file. I can verify that the String I feed it is being encrypted and written to the correct file, but when I try to read back from this file, the BufferedReader reports an EOF (null). The InputStream.available() method returns 0. I can assure that the file is there, is being found, and that the InputStream itself is not null. Can anybody tell me what might cause this?
Reading/Writing encrypted Object works beautifully (CorruptedStreamException is good here):
private static void testWriteObject() {
String path = "derp.derp";
Derp start = new Derp("Asymmetril: " + message, 12543, 21.4, false);
FilesEnDe.writeEncryptedObject(key, "derp.derp", start);
echo("original");
echo(">"+start);
Object o;
try {
ObjectInputStream ois = new ObjectInputStream(ResourceManager.getResourceStatic(path));
o = ois.readObject();
echo("encrypted");
echo(">"+o);
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
o = FilesEnDe.readEncryptedObject(key, path);
echo("decrypted");
echo(">"+o);
}
Output:
original
>Asymmetril: WE CAME, WE SAW, WE CONQUERED.; 12543; 21.4; false
[RM] > Trying to load resource: derp.derp
java.io.StreamCorruptedException
[RM] > Trying to load resource: derp.derp
decrypted
>Asymmetril: WE CAME, WE SAW, WE CONQUERED.; 12543; 21.4; false
Trying to decrypt the text file doesn't (note that the encrypted text is readable):
private static void testWriteFile() {
String path = "EncryptedOut.txt";
BufferedReader bis1, bis2;
try {
BufferedOutputStream os = new BufferedOutputStream(FilesEnDe.getEncryptedOutputStream(key, path));
os.write(message.getBytes());
os.flush();
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
echo("original");
echo(">"+message);
try {
bis1 = new BufferedReader (new InputStreamReader(ResourceManager.getResourceStatic(path)));
echo("encrypted");
echo(">" + bis1.readLine());
bis1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream is = FilesEnDe.getEncryptedInputStream(key, path);
InputStreamReader isr = new InputStreamReader(is);
bis2 = new BufferedReader (isr);
echo("bits in stream? " + is.available());
echo("decrypted");
echo(">"+bis2.readLine());
bis2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Output:
original
>WE CAME, WE SAW, WE CONQUERED.
encrypted
>¤ƒ]£¬Vß4E?´?ùûe
[RM] > Trying to load resource: EncryptedOut.txt
bytes in stream? 0
decrypted
>null
The code used to create the CipherInputStream:
public static InputStream getEncryptedInputStream(String key, String path) {
try {
InputStream is = ResourceManager.getResourceStatic(path);
SecretKeySpec keyspec = new SecretKeySpec(getHash(key),"AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, keyspec);
return new CipherInputStream(is,c);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
THE PROBLEM OCCURS WHEN I TRY TO USE A CIPHERINPUTSTREAM TO DECRYPT THE FILE AND RETRIEVE THE ORIGINAL STRING.
However, the problem arises when I try to read from an encrypted text file.
There is no such thing as an 'encrypted text file'. The result of encryption is binary, not text.
I can verify that the String I feed it is being encrypted and written to the correct file, but when I try to read back from this file, the BufferedReader reports an EOF (null).
You shouldn't be using a BufferedReader. It isn't text, it is binary. Use a BufferedInputStream.
It didn't matter whether I wrote via a PrintWriter or a BufferedOutputStream, nor whether I read with a Reader or not. Turns out, I forgot to close the OutputStream that created the file. As soon as I added that one little line, everything began working. Thank you to Antoniossss for suggesting I redo the broken part of my method. I wonder why Eclipse didn't mention a resource leak about it...
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();
}
}