Convert string and byte[] to file in JAVA - java

I have an interface with this strings and bytes array
public interface EmailAttachment {
String getFileName();
String getFileVersion();
byte[] getContent();
String getType();
}
i want to put all of this in a file, in my class Service how could i called?:
#Override
public Boolean sendEmail(EmailAttachment attachment) {
File file = new File( "HERE,I want to bring everything");
uploadFile(file);
}
If i use attachment.getFileName(),attachment.getFileVersion(),attachment.getContent(),attachment.getType()
it brings me an error because the file needs a path

try this out create a File object with the file name and pass it on to FileOutputStream.
OutputStream accepts byte array to store it in file, once uploading done close the stream.
String FILENAME = "";
File file = new File(FILENAME);
OutputStream os = new FileOutputStream(file);
// here you can write bytes to file using FileOutputStream
os.write(bytes);
// Close the file
os.close();

Related

encode/decode file in java with Base64

I've written a encode/decode file in Java like below
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class Test {
public static void encodeFile(String inputfile, String outputfile) throws IOException {
byte[] input_file = Files.readAllBytes(Paths.get(inputfile));
byte[] encodedBytes = Base64.getEncoder().encode(input_file);
String encodedString = new String(encodedBytes);
File ff = new File(outputfile);
FileOutputStream fileOut = new FileOutputStream(ff);
OutputStreamWriter outStream = new OutputStreamWriter(fileOut);
outStream.write(encodedString);
outStream.flush();
}
public static void decodeFile(String encodedfilecontent, String decodedfile) throws IOException {
byte[] decoded = Base64.getDecoder().decode(encodedfilecontent);
String decodedString = new String(decoded);
File ff = new File(decodedfile);
FileOutputStream fileOut = new FileOutputStream(ff);
OutputStreamWriter outStream = new OutputStreamWriter(fileOut);
outStream.write(decodedString);
outStream.flush();
}
public static void main(String[] args) throws IOException {
String inputfile = "C:\\Users\\John\\Desktop\\Files.zip";
String outputfile = "C:\\Users\\John\\Desktop\\encoded.txt";
encodeFile(inputfile, outputfile);
String encodedfilecontent = new String(Files.readAllBytes(Paths.get(outputfile)));
String decodedfile = "C:\\Users\\John\\Desktop\\DecodedFiles.zip";
decodeFile(encodedfilecontent, decodedfile);
}
}
The above code has 2 methods:
1- To encode file to Base64 and write it in a text file
2- To decode the text file and write it back into a new file
All the input/output files are in desktop
I've test this and this encode and decode methods only work if inputfile is simple text file. If the input file is an image or a zip file like this example, the decoded file will be broken. Can you explain why it is broken like this?
Is there anyway to universally encode any type of file to Base64 and decode it back? If yes can you tweak the above code to do that?
You are not closing the files. Also there is the mentioned problem when you use text (String/Reader/Writer) for binary data: corrupt data, slower, double memory, platform dependent when not specifying the encoding.
The optimal solution is not to take the bytes in memory, additionally making a 8/5 larger byte array with base 64.
Use try-with-resources to automatically close the files, even on an exception (like illegal Base 64 chars).
public static void encodeFile(String inputFile, String outputFile)
throws IOException {
Path inPath = Paths.get(inputFile);
Path outPath = Paths.get(outputFile);
try (OutputStream out = Base64.getEncoder().wrap(Files.newOutputStream(outPath))) {
Files.copy(inPath, out);
}
}
public static void decodeFile(String encodedfilecontent, String decodedfile)
throws IOException {
Path inPath = Paths.get(encodedfilecontent);
Path outPath = Paths.get(decodedfile);
try (InputStream in = Base64.getDecoder().wrap(Files.newInputStream(inPath))) {
Files.copy(in, outPath);
}
}
In your decodeFile method you should not convert the byte[] into a String. This will use the default platform character encoding and some bytes may not make sense in that encoding. Instead, you should write the byte array in the output file directly.

How to save a file in the Downloads directory?

My Code is:
String MyFile = "Riseone.dat";
String MyContent = "This is My file im writing\r\n";
File file;
FileOutputStream outputStream;
try {
file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS),MyFile);
outputStream = new FileOutputStream(file);
outputStream.write(MyContent.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
When I try this code MyFile creates in data/data/appfolder/files/Riseone.dat
but I want to create a file in DIRECTORY_DOWNLOADS.
also I want the file to write in append for next write action.
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), MyFile); corresponds to the file inside the Downloads directory of external shared storage. You might have seen older file in internal storage. Check it carefully.
If you want to append the data for next write, use append mode to create FileOutputStream using another constructor public FileOutputStream(File file, boolean append)
outputStream = new FileOutputStream(file, true);

Large file upload using FileInputStream and FileOutputStream

HttpExchange exchange;
OutputStream responseBody = null;
try{
File fileVal = new File(file);
InputStream inVal = new FileInputStream(fileVal);
exchange.sendResponseHeaders(HTTP_OK, fileVal.length());
responseBody = exchange.getResponseBody();
int read;
byte[] buffer = new byte[4096];
while ((readVal = inVal.read(buffer)) != -1){
responseBody.write(buffer, 0, readVal);
}
} catch (FileNotFoundException e){
//uh-oh, the file doesn't exist
} catch (IOException e){
//uh-oh, there was a problem reading the file or sending the response
} finally {
if (responseBody != null){
responseBody.close();
}
}
I am tring to upload large video file as chunks .while doing the operation I am getting the following error.
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.io.File(org.springframework.web.multipart.commons.CommonsMultipartFile)
any anyone guide me to solve this.
File fileVal = new File(file);
Here file is org.springframework.web.multipart.commons.CommonsMultipartFile type and you are trying to create File object by passing CommonsMultipartFile object in constructor and File class does not have constructor of CommonsMultipartFile type.
Check here for File Class Constructor
You Need to get Bytes from file object and create a java.io.File object.
Convert MultiPartFile into File
The error message descripes the failure perfectly. There is no constructor for the class File that accept a parameter of the type org.springframework.web.multipart.commons.CommonsMultipartFile.
Try using the path to the file you want to open. For example:
String path = "/path/to/your/file.txt";
File fileVal = new File(path);
Alternatively you can use the getInputStream() method from CommonsMultipartFile.
InputStream inVal = file.getInputStream();

Writing a file from byte array into a zip file

I'm trying to write a file name "content" from a byte array into an existing zip file.
I have managed so far to write a text file \ add a specific file into the same zip.
What I'm trying to do, is the same thing, only instead of a file, a byte array that represents a file. I'm writing this program so it will be able to run on a server, so I can't create a physical file somewhere and add it to the zip, it all must happen in the memory.
This is my code so far without the "writing byte array to file" part.
public static void test(File zip, byte[] toAdd) throws IOException {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
Path path = Paths.get(zip.getPath());
URI uri = URI.create("jar:" + path.toUri());
try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
Path nf = fs.getPath("avlxdoc/content");
try (BufferedWriter writer = Files.newBufferedWriter(nf, StandardOpenOption.CREATE)) {
//write file from byte[] to the folder
}
}
}
(I tried using the BufferedWriter but it didn't seem to work...)
Thanks!
Don't use a BufferedWriter to write binary content! A Writer is made to write text content.
Use that instead:
final Path zip = file.toPath();
final Map<String, ?> env = Collections.emptyMap();
final URI uri = URI.create("jar:" + zip.toUri());
try (
final FileSystem zipfs = FileSystems.newFileSystem(uri, env);
) {
Files.write(zipfs.getPath("into/zip"), buf,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
(note: APPEND is a guess here; it looks from your question that you want to append if the file already exists; by default the contents will be overwritten)
You should use a ZipOutputStream to access the zipped file.
ZipOutputStream lets you add an entry to the archive from whatever you want, specifying the name of the entry and the bytes of the content.
Provided you have a variable named theByteArray here is a snippet to add an entry to an zip file:
ZipOutputStream zos = new ZipOutputStream(/* either the destination file stream or a byte array stream */);
/* optional commands to seek the end of the archive */
zos.putNextEntry(new ZipEntry("filename_into_the_archive"));
zos.write(theByteArray);
zos.closeEntry();
try {
//close and flush the zip
zos.finish();
zos.flush();
zos.close();
}catch(Exception e){
//handle exceptions
}

Control Uploaded file types (only specific extension can be uploaded)

i have a stupid question here i'm implementing upload button with vaadin and i want the users to upload only compressed files (.zip,.rar..), imake a search but i didn't find something useful :
so i tried to do this , i know it's not good solution because the user already uploaded the selected file :
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
String fileName ;
String userHome = System.getProperty( "user.home" );
try {
// Open the file for writing.
file = new File(userHome+"/kopiMap/runtime/uploads/report/" + filename);
fileName= file.getName();
//Here i will get file extension
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
Notification.show(
"Could not open file<br/>", e.getMessage(),
Notification.TYPE_ERROR_MESSAGE);
return null;
}
return fos; // Return the output stream to write to
}
So how to do it before uploading
you can check the mimeType and if it is application/zip
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
if(mimeType.equals("application/zip"))
//Here you can restrict
You can add this and it will work (all done by HTML 5 and most browser support now accept attribute) - this is example for .csv files:
upload.setButtonCaption("Import");
JavaScript.getCurrent().execute("document.getElementsByClassName('gwt-FileUpload')[0].setAttribute('accept', '.csv')");

Categories