Modify Code to Download File to Music Directory {Android} - java

Currently,The code below only saves downloaded files into the Download Directory on the phone storage.Hence the downloaded file cannot be accessed by other applications because it is private.
My Question is how do i modify the code i pasted below to save the files downloaded, into the Music Directory on the Sd card.
I pasted the full code below:
private void downloadFile() {
new DownloadFileThread().start();
}
class DownloadFileThread extends Thread {
#Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
FileOutputStream fos = getOutStream(fileName);
int count = 0;
byte buf[] = new byte[1024];
do {
int numread = is.read(buf);
count += numread;
progress = (int) (((float) count / length) * 100);
mHandler.sendEmptyMessage(DOWNLOAD);
if (numread <= 0) {
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
// 写入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);
fos.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mDownloadDialog.dismiss();
}
}
/**
* #param fileName
* #return
* #throws FileNotFoundException
*/
#SuppressWarnings("deprecation")
#SuppressLint("WorldReadableFiles")
private FileOutputStream getOutStream(String fileName) throws FileNotFoundException{
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
String sdpath = Environment.getExternalStorageDirectory()
+ "/";
mSavePath = sdpath + "download";
File file = new File(mSavePath);
if (!file.exists()) {
file.mkdir();
}
File saveFile = new File(mSavePath, fileName);
return new FileOutputStream(saveFile);
}else{
mSavePath = mContext.getFilesDir().getPath();
return mContext.openFileOutput(fileName , Context.MODE_WORLD_READABLE);
}
}
}

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

Java save mp3 file

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();

.zip file isn't deleted but neither throw any exception

I've created an app with utilities I usually use on my pc (like sending shutdown to cmd.exe) and as some friends asked me to give it to them I was trying to add an update system that checks for updates on a server to make it easier that their version is always updated.
The thing is that I've been over the net searching any solution but all of them just tell to use .close() and my file has it right after stop needing it. When I run it everything works fine and there are no exceptions thrown, so I just dunno what can be wrong.
Whole class:
public class Main_Gui extends JFrame {
private Thread worker;
private final String root = "update/";
private JTextArea outText;
private JButton cancel;
private JButton launch;
private JScrollPane sp;
private JPanel pan1;
private JPanel pan2;
private String zipFile = "Actualización.zip";
private String path = "http://ritsu.hol.es/url.html";
private String TITLE = "RitsUtilities | Actualizador";
public Main_Gui() {
initComponents();
outText.setText("Conectando con el servidor...");
download();
}
private void initComponents() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setTitle(TITLE);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pan1 = new JPanel();
pan1.setLayout(new BorderLayout());
pan2 = new JPanel();
pan2.setLayout(new FlowLayout());
outText = new JTextArea();
sp = new JScrollPane();
sp.setViewportView(outText);
launch = new JButton("Ejecutar RitsUtilities");
launch.setEnabled(false);
launch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] run = { "java", "-jar", "RitsUtilities.jar" };
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
launch();
}
});
pan2.add(launch);
cancel = new JButton("Salir");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pan2.add(cancel);
pan1.add(sp, BorderLayout.CENTER);
pan1.add(pan2, BorderLayout.SOUTH);
add(pan1);
pack();
setSize(500, 400);
setLocationRelativeTo(null);
}
private void download() {
worker = new Thread(new Runnable() {
public void run() {
try {
downloadFile(getDownloadLinkFromHost());
unzip();
copyFiles(new File(root), new File("").getAbsolutePath());
cleanup();
launch.setEnabled(true);
outText.setText(outText.getText() + "\n¡Actualización completada con éxito!");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Ha ocurrido un error al descargar y descomprimir la actualización.", "Error 1", JOptionPane.WARNING_MESSAGE);
}
}
});
worker.start();
}
private void launch() {
String[] run = { "java", "-jar", "update app.jar" };
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
}
private void cleanup() {
outText.setText(outText.getText() + "\nLimpiando archivos temporales...");
remove(new File(root));
new File(root).delete();
}
private void remove(File f) {
File[] files = f.listFiles();
for (File ff : files) {
if (ff.isDirectory()) {
remove(ff);
ff.delete();
} else {
ff.delete();
}
}
}
private void copyFiles(File f, String dir) throws IOException {
File[] files = f.listFiles();
for (File ff : files) {
if (ff.isDirectory()) {
new File(dir + "/" + ff.getName()).mkdir();
copyFiles(ff, dir + "/" + ff.getName());
} else {
copy(ff.getAbsolutePath(), dir + "/" + ff.getName());
}
}
}
public void copy(String srFile, String dtFile) throws FileNotFoundException, IOException {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
private void unzip() throws IOException {
int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(zipFile);
Enumeration e = zipfile.entries();
(new File(root)).mkdir();
while (e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
outText.setText(outText.getText() + "\nExtrayendo: " + entry);
if (entry.isDirectory())
(new File(root + entry.getName())).mkdir();
else {
(new File(root + entry.getName())).createNewFile();
is = new BufferedInputStream(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(root + entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
is.close();
}
}
}
private void downloadFile(String link) throws MalformedURLException, IOException {
URL url = new URL(link);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
long max = conn.getContentLength();
outText.setText(outText.getText() + "\n" + "Descargando archivo...\nTamaño de la actualización(comprimida): " + max + " Bytes");
BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File(zipFile)));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
int in = 0;
while ((bytesRead = is.read(buffer)) != -1) {
in += bytesRead;
fOut.write(buffer, 0, bytesRead);
}
fOut.flush();
fOut.close();
is.close();
outText.setText(outText.getText() + "\n¡Descarga completada!");
}
private String getDownloadLinkFromHost() throws MalformedURLException, IOException {
URL url = new URL(path);
InputStream html = null;
html = url.openStream();
int c = 0;
StringBuilder buffer = new StringBuilder("");
while (c != -1) {
c = html.read();
buffer.append((char) c);
}
return buffer.substring(buffer.indexOf("[url]") + 5, buffer.indexOf("[/url]"));
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main_Gui().setVisible(true);
}
});
}
}
EDIT: changed private String zipFile = "Actualización.zip"; to private String zipFile = "Update.zip"; but still just deleting temp files/directories but not that "Update.zip" folder that the app downloads.
The File#delete() method you are using doesn't throw an error if the file can't be deleted, it returns false. This is documented in the Javadoc, together with an alternative solution (emphasize mine):
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
Finally it's working, just added a forced delete on run() inside download() so now my code looks like
public void run() {
try {
downloadFile(getDownloadLinkFromHost());
unzip();
copyFiles(new File(root), new File("").getAbsolutePath());
cleanup();
launch.setEnabled(true);
+ System.gc();
+ File tmpf = new File(zipFile);
+ tmpf.deleteOnExit();
outText.setText(outText.getText() + "\n¡Actualización completada con éxito!");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Ha ocurrido un error al descargar y descomprimir la actualización.", "Error 1", JOptionPane.WARNING_MESSAGE);
}
}
I'm pretty sure that there are way better ways to do this, but that one seems to work for me.
Thanks to everyone that answered and tried to help me. =D
I would suggest improving your remove(File f) method. Add some checks for the Boolean return value of ff.delete(), that will tell you if the file is actually being deleted or not.
Also, you could add some logs into that method, so you could debug what is actually doing, perhaps it's not seeing the files or something.
One last comment. You should make your code more modular. Create more abstractions and give each of them a simple task. That is the essence of Object Oriented Design. Then, you can program some JUnit tests for each object, and you can run the tests every time you make a change. I reccomend you give a look to this article on Cohesion

Java - sending a file over socket - file isn't received fully

i am really stuck with a little project i'm doing. I am trying to send music files (only .wav) over a socket from a server to a client. Everything works perfectly fine (i think...) except that the file that is received by the client isn't complete. I can't play the file and I can see that it is a bit smaller than the one the server has. What am I doing not right?
Here is the server code:
private Socket client;
private String filename;
private TBMCAudioServer ac;
private FileInputStream fis;
private BufferedOutputStream out;
int bufferSize = 0;
FileSender(Socket client, String filename, TBMCAudioServer ac){
this.client = client;
this.filename = filename;
this.ac = ac;
}
#Override
public void run(){
ac.ex.sendMessage(client, "[#preload#]" + filename);
File dir = new File(ac.getDataFolder() + File.separator + "music");
if(!dir.exists()){
dir.mkdir();
}
File file = new File(dir, filename + ".wav");
long length = file.length();
if(length > Integer.MAX_VALUE){
logger.info("File is too large.");
}
byte[] bytes = new byte[(int) length];
try{
fis = new FileInputStream(file);
out = new BufferedOutputStream(client.getOutputStream());
} catch (IOException e){
logger.info(e.getMessage());
}
int count;
try {
while((count = fis.read(bytes,0,bytes.length)) != -1){
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
} catch (IOException e) {
logger.info(e.getMessage());
}
}
and here you can see my client code:
private Socket server;
private String filename;
private AudioClient ac;
InputStream is = null;
FileOutputStream fos = null;
int bufferSize = 0;
FileReceiver(Socket server, String filename, AudioClient ac){
this.server = server;
this.filename = filename;
this.ac = ac;
}
#Override
public void run() {
try{
is = server.getInputStream();
bufferSize = server.getReceiveBufferSize();
ac.logConsole("Buffer size: " + bufferSize);
} catch (IOException ex){
ac.logConsole(ex.getMessage());
}
try{
fos = new FileOutputStream(AudioClient.util.getLineValue(3) + filename + ".wav");
} catch (FileNotFoundException e){
ac.logConsole(e.getMessage());
}
byte[] bytes = new byte[bufferSize];
int count;
try {
while((count = is.read(bytes, 0, bytes.length)) != -1){
fos.write(bytes, 0, count);
}
ac.logConsole("yay");
is.close();
fos.flush();
fos.close();
} catch (IOException e) {
ac.logConsole(e.getMessage());
}
}
Okay I managed to send the file fully so I can see it has the same size as where it came from with my new code. The only problem is that i'm sending a music file and I can't play the file that is sent. Maybe someone knows what the problem is?
Server code:
package me.Ciaran.simplefileserver;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleFileServer {
public final static int SOCKET_PORT = 13267; // you may change this
public final static String FILE_TO_SEND = "D:/server/plugins/TBMCAudioServer/music/DLTALL.wav"; // you may change this
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
final File myFile= new File(FILE_TO_SEND); //sdcard/DCIM.JPG
byte[] mybytearray = new byte[8192];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
try {
os = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
int read;
while((read = dis.read(mybytearray)) != -1){
dos.write(mybytearray, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null) servsock.close();
}
}
}
and here is the client code:
package me.Ciaran.simplefileclient;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SimpleFileClient {
public final static int SOCKET_PORT = 13267; // you may change this
public final static String SERVER = "127.0.0.1"; // localhost
public final static String
FILE_TO_RECEIVED = "C:/Users/Ciaran/Documents/TESTEN/music/DLTALL.wav"; // you may change this, I give a
// different name because i don't want to
// overwrite the one used by server...
public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloaded
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
InputStream in;
int bufferSize=0;
try {
bufferSize=sock.getReceiveBufferSize();
in=sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
String fileName = clientData.readUTF();
System.out.println(fileName);
OutputStream output = new FileOutputStream(FILE_TO_RECEIVED);
byte[] buffer = new byte[bufferSize];
int read;
while((read = clientData.read(buffer)) != -1){
output.write(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
}

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