Java save mp3 file - java

I am trying to create import images and mp3 files from one directory using a file chooser and save them to another . The images went fine but I cant seem to find out how to save the mp3 file .
Images
#Override
public void saveFile(File file) {
//Get image path
String imagePath = file.getAbsolutePath();
String imageName = file.getName();
System.out.println(imagePath);
//Read image
try {
bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
bufferedImage = ImageIO.read(new File(imagePath));
System.out.println("Reading complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
//write image
try {
f = new File("H:\\TestFolder\\images\\" + imageName); //output file path
ImageIO.write(bufferedImage, "jpg", f);
System.out.println("Writing complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
Mp3
#Override
public void saveFile(File file) {
try{
f = new File(file, "H:\\TestFolder\\test.mp3"); //file.getAbsolutePath();
}catch (Exception e) {
e.printStackTrace();
}
}

Use Files.copy(source, target, REPLACE_EXISTING);
https://docs.oracle.com/javase/tutorial/essential/io/copy.html

Try it like this:
File f = new File("H:\\TestFolder\\test.mp3");
InputStream is = new FileInputStream(f);
OutputStream outstream = new FileOutputStream(new File("H:\\TestFolder2\\blabla.mp3"));
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
outstream.close();

Related

The Pic's corrupted in screenshotting programmatically in Android Studio

this is the code for the screenshot that redirect the screenshot in /Pictures/Lones but the picture is corrupted every time that it is getting uploaded.
public void Saves(View view){
int count = 0;
File sdDirectory = Environment.getExternalStorageDirectory();
File subDirectory = new File(sdDirectory.toString() + "/Pictures/Lones");
if (subDirectory.exists()) {
File[] existing = subDirectory.listFiles();
for (File file : existing) {
if (file.getName().endsWith(".jpg") || file.getName().endsWith(".png")) {
count++;
}
}
} else {
subDirectory.mkdir();
}
if (subDirectory.exists()) {
File image = new File(subDirectory, "/drawing_" + (count + 1) + ".png");
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(image);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
this is the result every time it is getting screenshotted

Android: Deleted file but user data not free up. How can fix?

My app can get image add in to folder "photo" and delete it, but after deleted image in folder "photo" user data not free up although i checked files explorer in android studio and log really deleted. I save the file in internal storage (app private storage) not external. How i can fix?
public class InternalStorageHelper {
public static String saveToInternalStorage(Bitmap bitmapImage, Context context, String fileName) {
File directory = new File(context.getApplicationInfo().dataDir, "photo");
if (!directory.exists()) {
directory.mkdirs();
}
// Create imageDir
File myPath = new File(directory, fileName+ ".jpg");
FileOutputStream fos = null;
if (myPath.exists()) {
myPath.delete();
}
try {
fos = new FileOutputStream(myPath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
return myPath.getAbsolutePath();
}
public static Bitmap loadImageFromStorage(String path) {
try {
File f = new File(path);
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static void deleteFile(String path) {
File fdelete = new File(path);
if (fdelete.exists()) {
if (fdelete.delete()) {
Log.d("progress", "file Deleted :" + path);
} else {
Log.d("progress", "file not Deleted :" + path);
}
}
}
}

scale the image from the folder

I am trying to resize the picture with file chooser. It seems everything is file, but I can't open it after adding in folder.
public void metodAddpath(String fullPath) {
try {
File sourceFile = new File(fullPath);
BufferedImage bufferedimage = ImageIO.read(sourceFile);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedimage, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
FileOutputStream fileOutputStream = new FileOutputStream(
sourceFile);
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = is.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
is.close();
fileOutputStream.close();
//scaleImage(bufferedimage, 220, 220);
} catch(Exception e) {
e.printStackTrace();
}
}
After I push the button to save the image in folder.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Database base = new Database();
metodAddpath(jTextField1.getText());
base.addPictureResource(jTextField1.getText());
}
But when I am trying to add it in folder, there is a mistake.
I'm just going to come out and say it, none of this...
try {
File sourceFile = new File(fullPath);
BufferedImage bufferedimage = ImageIO.read(sourceFile);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedimage, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
FileOutputStream fileOutputStream = new FileOutputStream(
sourceFile);
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = is.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
is.close();
fileOutputStream.close();
//scaleImage(bufferedimage, 220, 220);
} catch(Exception e) {
e.printStackTrace();
}
makes sense.
You're reading the image, writing it to a ByteArrayOutputStream, piping that through a InputStream which you're then using to write the contents to another file via a FileOutputStream ... why?!
Something like...
File sourceFile = new File(fullPath);
try {
BufferedImage bufferedimage = ImageIO.read(sourceFile);
//scaleImage(bufferedimage, 220, 220);
// Beware, this is overwriting the existing file
try (FileOutputStream fileOutputStream = new FileOutputStream(sourceFile)) {
ImageIO.write(bufferedimage, "jpg", fileOutputStream);
}
} catch(Exception e) {
e.printStackTrace();
}
would do the same job, is easier to read and probably more efficient...
I doubt this will answer you question, but it might reduce some of the confusion
Finally, I found the way how to scale the image before saving in the folder. First I would like to add a listener for the button and get the image with file chooser.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpeg", "jpg", "png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
if(result ==JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
//GET ABSOLUTE PATH OF PICTURES
jTextField1.setText(selectedFile.getAbsolutePath());
//addPicture.setText(selectedFile.getName());
//GET NAME OF PICTURES
//getPicName = selectedFile.getName();
} else if(result == JFileChooser.CANCEL_OPTION) {
System.out.println("File not found!");
}
}
After I am adding a listener for another button that is responsible for adding a picture to the folder. Here is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
addPicture(jTextField1.getText());
}catch(Exception e) {
e.printStackTrace();
}
}
And finally, let's add two functions:
public void addPicture(String fullPath) throws IOException {
File sourceFile = new File(fullPath);
try {
BufferedImage bufferedimage = ImageIO.read(sourceFile);
// add method scaleImage(bufferedimage, 220, 220) in ImageIO.write(scaleImage(bufferedimage, 220, 220), "jpg", fileOutputStream)
try (FileOutputStream fileOutputStream = new FileOutputStream("/my files/NetBeans IDE 8.2/NewDataBase/src/newdatabase/images/" + sourceFile.getName())) {
ImageIO.write(scaleImage(bufferedimage, 220, 220), "jpg", fileOutputStream);
}
} catch(Exception e) {
e.printStackTrace();
}
Add don't forget about the important method
public BufferedImage scaleImage(BufferedImage img, int width, int height) {
int imgWidth = img.getWidth();
int imgHeight = img.getHeight();
if (imgWidth*height < imgHeight*width) {
width = imgWidth*height/imgHeight;
} else {
height = imgHeight*width/imgWidth;
}
BufferedImage newImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = newImage.createGraphics();
try {
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.clearRect(0, 0, width, height);
g.drawImage(img, 0, 0, width, height, null);
}
finally {
g.dispose();
}
return newImage;
}
}
Thanks averyone for help. I would like to say thanks to MadProgrammer. You're a genius, man.

Images corrupt on local storage after bringing them in from a URL

So I have it that when an in-app item is purchased the image they purchased is downloaded onto the phone. Works fine on external storage but I want it on INTERNAL storage. I'm using Picasso to load it into a bitmap then put into a PNG file. I'm not sure why it's getting corrupted along the way on internal storage. When the SD card is perfectly fine.
Anyone have any ideas why this is happening? Thanks!
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
//Internal storage
String path = getFilesDir().getAbsolutePath();
File imageFile = new File(path, "image.png");
FileOutputStream fos = null;
//TO SD Storage
File file = new File(
Environment.getExternalStorageDirectory().getPath());
File fileName = new File(file, "scrone.png");
if (isSDPresent) {
if (!fileName.getName().equals("scrone.png")) {
try {
FileOutputStream ostream = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
} else if (fileName.getName().equals("scrone.png")) {
try {
fileName = new File(file, "scrtwo.png");
FileOutputStream ostream = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//I'm sorry for the mess you're about to witness
else if(!imageFile.exists()){
try {
Log.d(TAG, "File doesn't exist");
fos = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
else if(imageFile.exists())
{
try
{
Log.d(TAG, "File does exist");
imageFile = new File("image2.png");
fos = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 75, fos);
fos.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}).start();
}

Zip File is Invalid?

So the code below is for a Bukkit server. What it does is zip all of the files in the server directory and puts the zip file in a "backups" folder. It works... to some extent. The files do indeed get copied and zipped, however if I click on the file, there's nothing in it (even though I know there is because it shows the file size next to it) and when I try to unzip it, windows gives me an error stating that the zip file is invalid. Any ideas why? Thanks :)
public class Backup extends Thread{
private static Backup instance;
public static Backup getInstance(){
return instance;
}
public static void newRef(){
instance = new Backup();
}
public void backup(final CommandSender sender) {
new Thread() {
public void run() {
sender.sendMessage(MessageManager.getChatPrefix() + "Starting backup...");
Backup.this.startBackup();
sender.sendMessage(MessageManager.getChatPrefix() + "Done!");
}
}.start();
}
public void backup() {
new Thread() {
public void run() {
Backup.this.startBackup();
}
}.start();
}
public void zipDir(String dir2zip, ZipOutputStream zos){
try{
File zipDir = new File(dir2zip);
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
for (String file : dirList) {
File f = new File(zipDir, file);
if (f.isDirectory()) {
String filePath = f.getPath();
zipDir(filePath, zos);
}else{
FileInputStream fis = new FileInputStream(f);
ZipEntry anEntry = new ZipEntry(f.getPath());
zos.putNextEntry(anEntry);
while ((bytesIn = fis.read(readBuffer)) != -1) {
zos.write(readBuffer, 0, bytesIn);
}
fis.close();
}
}
}catch(Exception e){
}}
public void startBackup(){
try {
File root = new File(".");
File bfolder = new File(root.getAbsolutePath() + "/backup/");
if (!bfolder.exists())
bfolder.mkdir();
File backup = new File(bfolder.getAbsolutePath() + "/backup.zip");
if (!backup.exists())
backup.createNewFile();
try{
ZipOutputStream zs = new ZipOutputStream(new FileOutputStream(backup));
System.out.println(MessageManager.getConsolePrefix() + "Zipping files...");
zipDir(root.getAbsolutePath(), zs);
zs.close();
System.out.println(MessageManager.getConsolePrefix() +"Done!");
}catch (Exception e){}
}catch(Exception e){
e.printStackTrace();
}
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date dateTime = new java.util.Date();
String date = dateFormat.format(dateTime);
List<World> worlds = Bukkit.getWorlds();
Object[] theWorlds = worlds.toArray();
String path = new File("").getAbsolutePath();
for(int i=0; i<theWorlds.length; i++){
World w = (World) theWorlds[i];
try {
w.save();
} catch (Exception e1) {}
String wNam = w.getName();
File srcFolder = new File(path + File.separator + wNam);
File destFolder = new File(Main.getInstance().getDataFolder().getAbsolutePath() + File.separator + "World Backups" + File.separator + date + File.separator + wNam);
destFolder.mkdirs();
if(srcFolder.exists()){
try{
Copier.copyFolder(srcFolder,destFolder);
}catch(IOException e){}
}
}
}
}
class Copier{
public static void copyFolder(File src, File dest) throws IOException{
if(src.isDirectory()){
if(!dest.exists())
dest.mkdir();
String files[] = src.list();
for (String file : files) {
File srcFile = new File(src, file);
File destFile = new File(dest, file);
copyFolder(srcFile,destFile);
}
}else{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0)
out.write(buffer, 0, length);
in.close();
out.close();
}
}
}

Categories