Spring rest upload file is corrupted - java

I have a java application which uses spring rest to upload a jar file.But the uploaded file is corrupted and I am not able to access the jar file from the server.Please help.
fileloc = fileloc.replace("$", "/");
String filename = uploadedFileRef.getOriginalFilename();
String path = fileloc + filename;
byte[] buffer = new byte[1000];
File outputFile = new File(path);
FileInputStream reader = null;
FileOutputStream writer = null;
int totalBytes = 0;
try {
outputFile.createNewFile();
reader = (FileInputStream) uploadedFileRef.getInputStream();
writer = new FileOutputStream(outputFile);
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer);
totalBytes += bytesRead;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

You call
writer.write(buffer);
so you write always the buffer size. Imagine the last read reads 10 bytes only but you will write 1000 bytes anyway.
Use
write(buffer, 0, bytesRead );
Or just check the question

Related

How to unzip zip file in JCIFS

I have zip file on remote server, which I am accessing using JCIFS. I want to extract contents of that zip on remote server only. tried :
private void unzipFile(SmbFile zipFile) {
try {
String destPath = "//SHARED-PC/reports/";
int BUFFER_SIZE = 4096;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipFile.getInputStream().read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}catch(Exception e) {
logger.error(" Error while unzipping zip file "+zipFile+" "+zipFile.getName());
e.printStackTrace();
}
}
But its alwayts reslting in errors
1. Access is Denied
2. I changed given path of dest folder - (The filename, directory name, or volume label syntax is incorrect)
Can someone suggest how it can be done? Thanx in advance
Update:
As per Petesh suggestion I used ZipInputStream to extract files from zip file.
i tried :
private static void unzip(SmbFile zipFilePath, String destDir) throws SmbException {
System.out.println(" Unzipping :: "+zipFilePath); //smb://WIN-B3TN6C0DC94/My_daily_reports/19-5-2018/Success/100-Sales-Records-19-5-2018.zip
System.out.println(" destdir is :: "+destDir); // smb://WIN-B3TN6C0DC94/My_daily_reports/19-5-2018/Success/
try {
ZipInputStream zis = new ZipInputStream(zipFilePath.getInputStream());
ZipEntry ze = zis.getNextEntry();
String fileName = ze.getName();
File newFile = new File(destDir);
System.out.println("newfile Path : "+newFile.getPath());
byte[] buf = new byte[1024];
String outputFilepathAndName = newFile.getPath() + File.separator + fileName;
System.out.println("outputFilepathAndName :: "+outputFilepathAndName);
OutputStream outputStream = new FileOutputStream(fileName);
while(ze != null){
int length;
while((length = zis.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
}
System.out.println("Write done // flushing now... ");
zis.closeEntry();
zis.close();
outputStream.close();
System.out.println(" UNZIP SUCCESSFUL "+fileName);
} catch (Exception e) {
System.out.println(" UNZIP ERROR");
e.printStackTrace();
}
}
But it gets stuck in while loop. Can anyone suggest what is going wrong here. I tried using OutputStream and BufferedOutputStream as well.

Java decompression of files from solr server

I am getting error when i am trying to decompressing the files coming from server,but i am getting error of invalid bit length in while loop.Is there any problem with code or encoding.
byte[] buffer = new byte[1024];
FileInputStream fileInput = null;
FileOutputStream fileOutputStream = null;
GZIPInputStream gzipInputStream = null;
System.out.println(source_compressed_filepath);
System.out.println(destinaton_decompressed_filepath);
try {
fileInput = new FileInputStream(source_compressed_filepath);
gzipInputStream = new GZIPInputStream(fileInput);
fileOutputStream = new FileOutputStream(destinaton_decompressed_filepath);
int len;
while ((len = gzipInputStream.read(buffer)) >=0) {
fileOutputStream.write(buffer, 0, len);
}
System.out.println("The file" + source_compressed_filepath + " was DeCompressed successfully!"
+ destinaton_decompressed_filepath);
}catch (IOException ex) {
System.out.println(" error in file decompression " + source_compressed_filepath);
} finally {
// close resources
try {
fileOutputStream.close();
gzipInputStream.close();
} catch (IOException e) {
}
}

How to write files to an SD Card from the internet?

An example would be a simple image.
I have tried so many things and it just refuses to work despite making a whole lot of sense.
What I've done so far is I'm able to grab 25 pictures and add them to
/sdcard/app name/sub/dir/filename.jpg
They all appear there according to the DDMS but they always have a filesize of 0.
I'm guessing it's probably because of my input stream?
Here's my function that handles the downloading and saving.
public void DownloadPages()
{
for (int fileC = 0; fileC < pageAmount; fileC++)
{
URL url;
String path = "/sdcard/Appname/sub/dir/";
File file = new File(path, fileC + ".jpg");
int size=0;
byte[] buffer=null;
try{
url = new URL("http://images.bluegartr.com/bucket/gallery/56ca6f9f2ef43ab7349c0e6511edb6d6.png");
InputStream in = url.openStream();
size = in.available();
buffer = new byte[size];
in.read(buffer);
in.close();
}catch(Exception e){
}
if (!new File(path).exists())
new File(path).mkdirs();
FileOutputStream out;
try{
out = new FileOutputStream(file);
out.write(buffer);
out.flush();
out.close();
}catch(Exception e){
}
}
}
It just keeps giving me 25 files in that directory but all of their file sizes are zero. I have no idea why. This is practically the same code I've used in a java program.
PS...
If you're gonna give me a solution... I've already tried code like this. It doesn't work.
try{
url = new URL(urlString);
in = new BufferedInputStream(url.openStream());
fout = new FileOutputStream(filename);
byte data[] = new byte[1024];
int count;
System.out.println("Now downloading File: " + filename.substring(0, filename.lastIndexOf(".")));
while ((count = in.read(data, 0, 1024)) != -1){
fout.write(data, 0, count);
}
}finally{
System.out.println("Download complete.");
if (in != null)
in.close();
if (fout != null)
fout.close();
}
}
Here's an image of what my directories look like
http://oi48.tinypic.com/2cpcprm.jpg
A bit change to your second option, try it as following way,
byte data[] = new byte[1024];
long total = 0;
int count;
while ( ( count = input.read(data)) != -1 )
{
total += count;
output.write( data,0,count );
}
This one is different in while statement while ((count = in.read(data, 0, 1024)) != -1)
Using Guava something like this should work:
String fileUrl = "xxx";
File file = null;
InputStream in;
FileOutputStream out;
try {
Uri url = new URI(fileUrl);
in = url.openStream();
out = new FileOutputStream(file)
ByteStreams.copy(in, out);
}
catch (IOException e) {
System.out.println(e.toString());
}
finally {
in.close();
out.flush();
out.close();
}

Android : How to read file in bytes?

I am trying to get file content in bytes in Android application. I have get the file in SD card now want to get the selected file in bytes. I googled but no such success. Please help
Below is the code to get files with extension. Through this i get files and show in spinner. On file selection I want to get file in bytes.
private List<String> getListOfFiles(String path) {
File files = new File(path);
FileFilter filter = new FileFilter() {
private final List<String> exts = Arrays.asList("jpeg", "jpg", "png", "bmp", "gif","mp3");
public boolean accept(File pathname) {
String ext;
String path = pathname.getPath();
ext = path.substring(path.lastIndexOf(".") + 1);
return exts.contains(ext);
}
};
final File [] filesFound = files.listFiles(filter);
List<String> list = new ArrayList<String>();
if (filesFound != null && filesFound.length > 0) {
for (File file : filesFound) {
list.add(file.getName());
}
}
return list;
}
here it's a simple:
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Add permission in manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
The easiest solution today is to used Apache common io :
http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#readFileToByteArray(java.io.File)
byte bytes[] = FileUtils.readFileToByteArray(photoFile)
The only drawback is to add this dependency in your build.gradle app :
implementation 'commons-io:commons-io:2.5'
+ 1562 Methods count
Since the accepted BufferedInputStream#read isn't guaranteed to read everything, rather than keeping track of the buffer sizes myself, I used this approach:
byte bytes[] = new byte[(int) file.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytes);
Blocks until a full read is complete, and doesn't require extra imports.
Here is a solution that guarantees entire file will be read, that requires no libraries and is efficient:
byte[] fullyReadFileToBytes(File f) throws IOException {
int size = (int) f.length();
byte bytes[] = new byte[size];
byte tmpBuff[] = new byte[size];
FileInputStream fis= new FileInputStream(f);;
try {
int read = fis.read(bytes, 0, size);
if (read < size) {
int remain = size - read;
while (remain > 0) {
read = fis.read(tmpBuff, 0, remain);
System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
remain -= read;
}
}
} catch (IOException e){
throw e;
} finally {
fis.close();
}
return bytes;
}
NOTE: it assumes file size is less than MAX_INT bytes, you can add handling for that if you want.
If you want to use a the openFileInput method from a Context for this, you can use the following code.
This will create a BufferArrayOutputStream and append each byte as it's read from the file to it.
/**
* <p>
* Creates a InputStream for a file using the specified Context
* and returns the Bytes read from the file.
* </p>
*
* #param context The context to use.
* #param file The file to read from.
* #return The array of bytes read from the file, or null if no file was found.
*/
public static byte[] read(Context context, String file) throws IOException {
byte[] ret = null;
if (context != null) {
try {
InputStream inputStream = context.openFileInput(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int nextByte = inputStream.read();
while (nextByte != -1) {
outputStream.write(nextByte);
nextByte = inputStream.read();
}
ret = outputStream.toByteArray();
} catch (FileNotFoundException ignored) { }
}
return ret;
}
In Kotlin you can simply use:
File(path).readBytes()
You can also do it this way:
byte[] getBytes (File file)
{
FileInputStream input = null;
if (file.exists()) try
{
input = new FileInputStream (file);
int len = (int) file.length();
byte[] data = new byte[len];
int count, total = 0;
while ((count = input.read (data, total, len - total)) > 0) total += count;
return data;
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (input != null) try
{
input.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return null;
}
A simple InputStream will do
byte[] fileToBytes(File file){
byte[] bytes = new byte[0];
try(FileInputStream inputStream = new FileInputStream(file)) {
bytes = new byte[inputStream.available()];
//noinspection ResultOfMethodCallIgnored
inputStream.read(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
Following is the working solution to read the entire file in chunks and its efficient solution to read the large files using a scanner class.
try {
FileInputStream fiStream = new FileInputStream(inputFile_name);
Scanner sc = null;
try {
sc = new Scanner(fiStream);
while (sc.hasNextLine()) {
String line = sc.nextLine();
byte[] buf = line.getBytes();
}
} finally {
if (fiStream != null) {
fiStream.close();
}
if (sc != null) {
sc.close();
}
}
}catch (Exception e){
Log.e(TAG, "Exception: " + e.toString());
}
To read a file in bytes, often used to read binary files, such as pictures, sounds, images, etc.
Use the method below.
public static byte[] readFileByBytes(File file) {
byte[] tempBuf = new byte[100];
int byteRead;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
while ((byteRead = bufferedInputStream.read(tempBuf)) != -1) {
byteArrayOutputStream.write(tempBuf, 0, byteRead);
}
bufferedInputStream.close();
return byteArrayOutputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Android - file download problem - incomplete file

I have checked many code snippets, tried with and without buffer and I can't get to download whole file to SD card. The code I use currently is:
try {
url = new URL("http://mywebsite.com/directory/");
} catch (MalformedURLException e1) { }
String filename = "someKindOfFile.jpg"; // this won't be .jpg in future
File folder = new File(PATH); // TODO: add checking if folder exist
if (folder.mkdir()) Log.i("MKDIR", "Folder created");
else Log.i("MKDIR", "Folder not created");
File file = new File(folder, filename);
try {
conn = url.openConnection();
is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
is.close();
} catch (IOException e) { }
This code creates directory on SD card but downloads only 77 bytes of files. What might be the problem?
The error here is that he was writing the count variable converted to byte datatype instead of the bytes read from the input stream (those should be stored in a temporary byte[] buffer via bis.read(buffer))
The proper code block should be:
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(file);
int current = 0;
byte[] buffer = new byte[1024];
while ((current = bis.read(buffer)) != -1) {
fos.write(buffer, 0, current);
}
fos.close();
is.close();

Categories