AsyncTask downloaded files with 0B - java

I trying to download files with AsyncTask, and all files which are downloaded has 0b. I don't know how to do. Can somebody help? Please help me, I spend all day for this. Where is my mistake? I have never work with AsyncTask, I wrote this code with example.
some code:
public class DownloadProgramTask extends AsyncTask<Void,Void,Void> {
int id;
MYDBHelperFromApi mydbHelperFromApi;
Program program;
List<Asana> asanaList;
public DownloadProgramTask(int id, MYDBHelperFromApi mydbHelperFromApi){
this.id = id;
this.mydbHelperFromApi = mydbHelperFromApi;
}
#Override
protected Void doInBackground(Void...params) {
program = mydbHelperFromApi.getProgramForStart(id);
asanaList = program.getAsanasList();
final String FILE_PATH_PROGRAM_VOICE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Programs/Voice/"+id+"/";
List<String> voiceList = new ArrayList<>();
List<File> fileList = new ArrayList<>();
File dirVoice = new File(FILE_PATH_PROGRAM_VOICE);
fileList.add(dirVoice);
for (File f:fileList) {
if (!f.exists())
f.mkdirs();
}
for (Asana a:asanaList) {
File voiceFile = new File(dirVoice, a.getPose_id() + ".mp3");
if (!voiceFile.exists()) {
voiceList.add(a.getVoice());
download(MYurl.BASE_URL + a.getVoice(), voiceFile.getPath());
Log.e("LINK",MYurl.BASE_URL + a.getVoice());
Log.e("Path voice", "" + voiceFile.getPath());
}
}
return null;
}
public void download(String s, String Path_file) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(s);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d("Something went wrong"," "+s);
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(Path_file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
if (isCancelled()) {
input.close();
}
total += count;
}
} catch (Exception e) {
Log.e("Exception", e.toString());
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
}
}

Where are you writing the in output stream?
Add this line in while loop in download method:
outputStream.write(data, 0, count);

Have you tried do a flush before closing the FileOutputStream?
try to put output.flush(); before output.close();
try {
if (output != null) {
output.flush();
output.close();
}
if (input != null)
input.close();
} catch (IOException ignored) {
}

Related

copy file from local to server does work, from server to local does not

We are trying to copy a pdf from server to local folder and we keep getting this error:
Logon failure: unknown user name or bad password.
this is the function:
public void copyPasteFileFromNetwerkDriveToLocal(String source, String destFileUrl, String destFileName) {
InputStream in = null;
OutputStream out = null;
try {
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domain","user","password");
String remoteDocUrl = "smb:"+source; //The shared directory to store pictures
SmbFile remoteDocUrlFile = new SmbFile(remoteDocUrl, auth);
remoteDocUrlFile.connect(); //Try to connect
if (remoteDocUrlFile.exists()) {
String remoteDocUrlAndName = "smb:"+source;
SmbFile remoteDocFile = new SmbFile(remoteDocUrlAndName, auth);
remoteDocFile.connect(); //Try to connect
File localFile = new File(destFileUrl+destFileName);
in = new BufferedInputStream(new SmbFileInputStream(remoteDocFile));
out = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int len = 0; //Read length
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
out.flush(); //The refresh buffer output stream
}
}
catch (Exception e) {
String msg = "The error occurred: " + e.getLocalizedMessage();
System.out.println(msg);
}
finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}
catch (Exception e) {}
}
}
but the other way around does work with the same username and password:
public void copyPasteFileFromLocalToNetwerkDrive(String source, String destFileUrl, String destFileName) {
InputStream in = null;
OutputStream out = null;
try {
//Get a picture
File localFile = new File(source);
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domain","user","password");
String remoteDocUrl = "smb:"+destFileUrl; //The shared directory to store pictures
SmbFile remoteDocUrlFile = new SmbFile(remoteDocUrl, auth);
remoteDocUrlFile.connect(); //Try to connect
if (!remoteDocUrlFile.exists()) {
//maak alle directories
remoteDocUrlFile.mkdirs();
}
String remoteDocUrlAndName = "smb:"+destFileUrl+destFileName;
SmbFile remoteDocFile = new SmbFile(remoteDocUrlAndName, auth);
remoteDocFile.connect(); //Try to connect
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteDocFile));
byte[] buffer = new byte[4096];
int len = 0; //Read length
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
out.flush(); //The refresh buffer output stream
}
catch (Exception e) {
String msg = "The error occurred: " + e.getLocalizedMessage();
System.out.println(msg);
}
finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}
catch (Exception e) {}
}
}
does anyone know what we are doing wrong?
thanks in advance!
sincerely,
laurens wolf

Why can't I open this file in the assets folder? [duplicate]

I have may wifi2.txt file in my assets file directory in Android Studio. However, I keep getting a NULLPointException when I try to access it. My code is below: (Thanks so much in advance)
//CSV FILE READING
File file = null;
try {
FileInputStream is = new FileInputStream(file);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("wifi2.txt")));
String line;
Log.e("Reader Stuff",reader.readLine());
while ((line = reader.readLine()) != null) {
Log.e("code",line);
String[] RowData = line.split(",");
LatLng centerXY = new LatLng(Double.valueOf(RowData[1]), Double.valueOf(RowData[2]));
if (RowData.length == 4) {
mMap.addMarker(new MarkerOptions().position(centerXY).title(String.valueOf(RowData[0]) + String.valueOf(RowData[3])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Done with CSV File Reading
In Kotlin, we can achieve this :-
val string = requireContext().assets.open("wifi2.txt").bufferedReader().use {
it.readText()
}
File file = null;
try {
FileInputStream is = new FileInputStream(file);
Actually you are not using FileInputStream anywhere. Just use this piece of code
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("wifi2.txt")));
String line;
Log.e("Reader Stuff",reader.readLine());
while ((line = reader.readLine()) != null) {
Log.e("code",line);
String[] RowData = line.split(",");
LatLng centerXY = new LatLng(Double.valueOf(RowData[1]), Double.valueOf(RowData[2]));
if (RowData.length == 4) {
mMap.addMarker(new MarkerOptions().position(centerXY).title(String.valueOf(RowData[0]) + String.valueOf(RowData[3])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
Method to read a file FROM assets:
public static String readFile(AssetManager mgr, String path) {
String contents = "";
InputStream is = null;
BufferedReader reader = null;
try {
is = mgr.open(path);
reader = new BufferedReader(new InputStreamReader(is));
contents = reader.readLine();
String line = null;
while ((line = reader.readLine()) != null) {
contents += '\n' + line;
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
return contents;
}
Usage: String yourData = LoadData("wifi2.txt");
Where wifi2.txt is assumed to reside in assets
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
Reference
My solution using kotlin to load text from asset file
object AssetsLoader {
fun loadTextFromAsset(context: Context, file: String): String {
return context.assets.open(file).bufferedReader().use { reader ->
reader.readText()
}
}
}
use it like this:
val text = AssetsLoader.loadTextFromAsset(context, "test.json")

Java PrintWriter printing multiple blank lines at the beginning of each file

I have used PrintWriter for long time and I have never encounted with this problem. See below
When I open the csv file using excel the first element of the headerline disapeared.
To further investigate, I found a couple of blank lines inserted at the beginning when opening it using text file.
below is my code:
print header line:
public void printHubInboundHeader() {
try {
StringBuilder sb = new StringBuilder();
String headingPart1 = "Inbound_Hub, Date, Time,";
String headingPart2 = "Weight";
sb.append(headingPart1+headingPart2);
System.out.println(sb);
FileWriter.writeFile(sb.toString(),"filepath");
}
catch(Exception e) {
System.out.println("Something wrong when writting headerline");
e.printStackTrace();
}
}
print actual data:
public void printHubSummary(Hub hub, String filePath) {
try {
StringBuilder sb = new StringBuilder();
String h = hub.getHub_code();
String date = Integer.toString(hub.getGs().getDate());
String time = hub.getGs().getHHMMFromMinute(hub.getGs().getClock());
String wgt = Double.toString(hub.getIb_wgt());
sb.append(h+","+date+","+time+","+wgt);
// System.out.println("truck print line: " + sb);
FileWriter.writeFile(sb.toString(),filePath);
}
catch (Exception e) {
System.out.println("Something wrong when outputing truck summary file!");
e.printStackTrace();
}
}
the file writer code:
public class FileWriter {
private static String filenameTemp;
public static boolean creatFile(String name) throws IOException {
boolean flag = false;
filenameTemp = name + "";
System.out.println("write to file: "+filenameTemp);
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
else {
filename.delete();
filename.createNewFile();
flag = true;
}
return flag;
}
public static boolean writeFile(String newStr, String filename) throws IOException {
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
File file = new File(filename);
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
buf.append(filein);
fos = new FileOutputStream(file);
byte[] unicode = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
fos.write(unicode);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
public static void setFileName(String fileName){
filenameTemp = fileName;
}
}
I don't know if this is the only problem with your code, but every call to your FileWriter.writeFile adds a new Byte Order Marker to the file. This means you end up with several markers in the file, and this may confuse some tools.
To remove the extra BOM in FileWriter.writeFile, you can use the deleteCharAt method:
...
buf = buf.append(System.getProperty("line.separator"));
}
if (buf.length() > 0 && buf.charAt(0) == '\uFEFF') {
buf.deleteCharAt(0);
}
buf.append(filein);

Read a file from a FTP server but InputStream is always null

I want read files in a directory. I want add in:
List<String> nomi = new ArrayList<String>();
the linestring of file Nomi.txt.
With debug i view correctly the files in links(001.jpg 002.jpg 003.jpg) and ft(Nomi.txt), but in stream i have always null;
InputStream stream = f.retrieveFileStream(/*url_ftp + "/photo/"+ft*/ft);
my complete code is this:
private static abstract class GetLinksTask extends AsyncTask<String, Void, List<String>> {
protected List<String> doInBackground(String... urls) {
List<String> links = new ArrayList<String>();
String ft=null;
BufferedReader reader = null;
List<String> nomi = new ArrayList<String>();
FTPClient f = new FTPClient();
try {
int reply;
f.connect(url_ftp);
f.login(username,password );
reply = f.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
f.disconnect();
System.err.println("FTP server refused connection.");
}
FTPListParseEngine engine = f.initiateListParsing("photo");
while (engine.hasNext()) {
FTPFile[] files = engine.getNext(25); // "page size" you want
//FTPFile[] files = engine.getFiles(filter);
for (FTPFile file : files) {
if(file.getName().substring(file.getName().length()-3,file.getName().length()).equals("jpg")){
System.out.println(file.getName());
links.add(file.getName());
}else{
ft=file.getName();
InputStream stream = f.retrieveFileStream(/*url_ftp + "/photo/"+ft*/ft);
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
//nomi.add(reader.readLine());
}
System.out.println(file.getName());
}
//names=nomi;
}
}catch (IOException e) {
e.printStackTrace();
}finally {
if (reader != null)
try {
reader.close();
}catch (IOException logOrIgnore) {
}
}
return links;
}
protected abstract void postExecute(List<String> links);
protected void onPostExecute(List<String> lists) {
postExecute(lists);
}
}
Some tips?
thanks
It is not enough to create a Reader
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
and to close it:
reader.close();
Somewhere, in between, you'll actually have to read the data:
String line;
while( (line = reader.readLine()) != null ){
nomi.add( line );
}
I am explaining the full code of getting inputStream from FTP server and then how to read data from that inputstream. I am assuming, you are using TLS/SSL security layer.
public FTPSClient makeFTPConnection(String vserver, int vport, String vuser, String vpassword) {
LOGGER.debug("ENTRY");
try {
ftpClient = new FTPSClient();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ftpClient.connect(vserver, vport);
ftpClient.login(vuser, vpassword);
ftpClient.execPBSZ(0);
ftpClient.execPROT("P");
ftpClient.changeWorkingDirectory("/");
ftpClient.changeWorkingDirectory("/feeds");
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
/* // int reply=ftpClient.getReply();
String replyStr=ftpClient.getReplyString();
ftpClient.getAuthValue();*/
LOGGER.debug("EXIT");
return ftpClient;
}
Then after making the connection, we will check weather file exist at ftp or not.
public InputStream checkWOFileExistAtFTP(FTPSClient ftpClient, String host,String user, String filePath) throws IOException {
int returnCode;
// filePath="ftp://"+user+"#"+host+"/"+filePath;
InputStream inputStream = ftpClient.retrieveFileStream(filePath);
String dd=ftpClient.getReplyString();
returnCode = ftpClient.getReplyCode();
if (inputStream == null || returnCode == 550) {
return null;
}
return inputStream;
}
Now we already got the inputStream in above method now its time to read data from it.
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
System.out.println("Reading file start.");
char[] charBuffer = new char[8 * 1024];
StringBuilder builder = new StringBuilder();
int numCharsRead;
while ((numCharsRead = br.read(charBuffer, 0, charBuffer.length)) != -1) {
builder.append(charBuffer, 0, numCharsRead);
}
//will print all data
system.out.println(builder.toString());

Downloaded jar file corrupted

I've got this code that downloads a .jar file from a specific URL and places it into a specific folder. The jar file downloaded is a mod for a game, meaning that it has to be downloaded and run correctly without being corrupted.
The problem is, each time I try downloading the file, it ends up being corrupted in some way and causing errors when it is loaded.
This is my download code:
final static int size=1024;
public static void downloadFile(String fAddress, String localFileName, String destinationDir, String modID) {
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(fAddress);
outStream = new BufferedOutputStream(new
FileOutputStream(destinationDir+"/"+localFileName));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
System.out.println("Downloaded Successfully.");
System.out.println("File name:\""+localFileName+ "\"\nNo ofbytes :" + ByteWritten);
System.out.println("Writing info file");
WriteInfo.createInfoFile(localFileName, modID);
}catch (Exception e) {
e.printStackTrace();
}
finally {
try {
is.close();
outStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Any ideas what is wrong with this code?
Not sure if this will solve your problem but you should flush your buffer at the end.
outStream.flush();
your code look like quite right; try this
public static void downloadFromUrl(String srcAddress, String userAgent, String destDir, String destFileName, boolean overwrite) throws Exception
{
InputStream is = null;
FileOutputStream fos = null;
try
{
File destFile = new File(destDir, destFileName);
if(overwrite && destFile.exists())
{
boolean deleted = destFile.delete();
if (!deleted)
{
throw new Exception(String.format("d'ho, an immortal file %s", destFile.getAbsolutePath()));
}
}
URL url = new URL(srcAddress);
URLConnection urlConnection = url.openConnection();
if(userAgent != null)
{
urlConnection.setRequestProperty("User-Agent", userAgent);
}
is = urlConnection.getInputStream();
fos = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int len, totBytes = 0;
while((len = is.read(buffer)) > 0)
{
totBytes += len;
fos.write(buffer, 0, len);
}
System.out.println("Downloaded successfully");
System.out.println(String.format("File name: %s - No of bytes: %,d", destFile.getAbsolutePath(), totBytes));
}
finally
{
try
{
if(is != null) is.close();
}
finally
{
if(fos != null) fos.close();
}
}
}

Categories