Downloading some files - basic4android

I want to download a file and save it into my app folder. I have to download different files with different formats, but only one each time.
I've read that I have to use HttpUtils, but sample codes are to difficult for me (I'm too noob).
Can anyone upload any sample code?? Thanks!!

This should point you in the right direction:
URL u = new URL(urlString);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File file = new File(outputDirectoryFile, outputFileName);
OutputStream out = new FileOutputStream(file);
InputStream in = c.getInputStream();
byte[] buffer = new byte[4096];
while ( (int len1 = in.read(buffer)) > 0 ) {
out.write(buffer,0, len1);
}
in.close();
out.close();
c.disconnect();
Remember, you should never perform operations like this on the default UI tread. It could prompt the user to force close your app. Read more here:
http://developer.android.com/resources/articles/painless-threading.html

This is how I finally do:
imgurl = "http://dl.dropbox.com/u/25045/file.jpg"
HttpUtils.CallbackActivity = "myactivity" 'Current activity name.
HttpUtils.CallbackJobDoneSub = "JobDone"
HttpUtils.Download("Job1", imgurl)
Dim out As OutputStream
out = File.OpenOutput(File.DirInternal, "file.jpg", True)
File.Copy2(HttpUtils.GetInputStream(imgurl), out)
out.Close

Related

MalformedInputException: Input length = 1 while reading text file with Files.readAllLines(Path.get("file").get(0);

Why am I getting this error? I'm trying to extract information from a bank statement PDF and tally different bills for the month. I write the data from a PDF to a text file so I can get specific data from the file (e.g. ASPEN HOME IMPRO, then iterate down to what the dollar amount is, then read that text line to a string)
When the Files.readAllLines(Path.get("bankData").get(0) code is run, I get the error. Any thoughts why? Encoding issue?
Here is the code:
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\wmsai\\Desktop\\BankStatement.pdf");
PDFTextStripper stripper = new PDFTextStripper();
BufferedWriter bw = new BufferedWriter(new FileWriter("bankData"));
BufferedReader br = new BufferedReader(new FileReader("bankData"));
String pdfText = stripper.getText(Loader.loadPDF(file)).toUpperCase();
bw.write(pdfText);
bw.flush();
bw.close();
LineNumberReader lineNum = new LineNumberReader(new FileReader("bankData"));
String aspenHomeImpro = "PAYMENT: ACH: ASPEN HOME IMPRO";
String line;
while ((line = lineNum.readLine()) != null) {
if (line.contains(aspenHomeImpro)) {
int lineNumber = lineNum.getLineNumber();
int newLineNumber = lineNumber + 4;
String aspenData = Files.readAllLines(Paths.get("bankData")).get(0); //This is the code with the error
System.out.println(newLineNumber);
break;
} else if (!line.contains(aspenHomeImpro)) {
continue;
}
}
}
So I figured it out. I had to check the properties of the text file in question (I'm using Eclipse) to figure out what the actual encoding of the text file was.
Then, when creating the file in the program, encode the text file to UTF-8 so that Files.readAllLines could read and grab the data I wanted to get.

Solution to upload image file via WCF service?

Being surfing for last 3-4 days downloading, running and fixing issues with available demo projects online, none of them work so far.
I need to upload an image using WCF webservice. Where from client side end I like to upload it by means of form (multipart/form-data), including some file description.
Any solution working with proper answer? My mind is really stacked overflow trying different solution. One which I initially have I am able to upload a text file where file gets created with some extra content in it. I need to upload image file.
------------cH2ae0GI3KM7GI3Ij5ae0ei4Ij5Ij5
Content-Disposition: form-data; name=\"Filename\"
testing file gets upload...
When I upload image file, the image file is empty.
Initial Code (one implantation), method by means of which I get the .txt file as above, in case of image its blank (or say corrupt don't know)
private string uplaodFile(Stream stream)
{
StreamReader sr = new StreamReader(stream);
int length = sr.ReadToEnd().Length;
byte[] buffer = new byte[length];
stream.Read(buffer, 0, length);
FileStream f = new FileStream(Path.Combine(HostingEnvironment.MapPath("~/Upload"), "test.png"), FileMode.OpenOrCreate);
f.Write(buffer, 0, buffer.Length);
f.Close();
stream.Close();
return "Recieved the image on server";
}
another;
public Stream FileUpload(string fileName, Stream stream)
{
string FilePath = Path.Combine(HostingEnvironment.MapPath("~/Upload"), fileName);
int length = 0;
using (FileStream writer = new FileStream(FilePath, FileMode.Create))
{
int readCount;
var buffer = new byte[8192];
while ((readCount = stream.Read(buffer, 0, buffer.Length)) != 0)
{
writer.Write(buffer, 0, readCount);
length += readCount;
}
}
return returnJson(new { resp_code = 302, resp_message = "occurred." });
}

file not downloading properly

I am downloading a file from a url and saving it to a directory on my phone.
the path is: /private/var/mobile/Applications/17E4F0B0-0781-4259-B39D-37057D44B778/Documents/samplefile.txt
However, when i debug the file is created and downloaded. But, when i ad-hoc it and run the file. samplefile.txt is created but it's blank.
Code:
String directory = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine (directory, "samplefile.txt");
if (!File.Exists (filename)) {
File.Create (filename);
var webClient = new WebClient ();
webClient.DownloadStringCompleted += (s, e) => {
var text = e.Result; // get the downloaded text
File.WriteAllText (filename, text);
};
var url = new Uri (/**myURL**/);
webClient.Encoding = Encoding.UTF8;
webClient.DownloadStringAsync (url);
I modified your sample slightly and the following works for me.
The StreamReader is only there just to re-read in the contents of the file to confirm that its the same contents in the file as that of the downloaded file:-
If you put a breakpoint there also you can manually inspect same contents as downloaded.
string directory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filename = Path.Combine(directory, "samplefile.txt");
if (!File.Exists(filename))
{
var webClient = new WebClient();
webClient.DownloadStringCompleted += (s, e) =>
{
// Write contents of downloaded file to device:-
var text = e.Result; // get the downloaded text
StreamWriter sw = new StreamWriter(filename);
sw.Write(text);
sw.Flush();
sw.Close();
sw = null;
// Read in contents from device and validate same as downloaded:-
StreamReader sr = new StreamReader(filename);
string strFileContentsOnDevice = sr.ReadToEnd();
System.Diagnostics.Debug.Assert(strFileContentsOnDevice == text);
};
var url = new Uri("**url here**, UriKind.Absolute);
webClient.Encoding = Encoding.UTF8;
webClient.DownloadStringAsync(url);
}

Saving images into a folder in android?

Hello am using camera in my application.So i want to save Captured images into folder in gallery,floder name must be application name?please suggest me with some Example?
Thanks in advance
You can create any folder or file you want. Read this Android article Taking Photos Simply:
Add the Photo to a Gallery When you create a photo through an intent,
you should know where your image is located, because you said where to
save it in the first place. For everyone else, perhaps the easiest way
to make your photo accessible is to make it accessible from the
system's Media Provider.
The following example method demonstrates how to invoke the system's
media scanner to add your photo to the Media Provider's database,
making it available in the Android Gallery application and to other
apps.
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
Use below code and modify the path where you want to save your image.
mImageView.setDrawingCacheEnabled(true); Bitmap bitmap =
mImageView.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/app_name/saved_images"); newDir.mkdirs();
Random gen = new Random(); int n = 10000; n = gen.nextInt(n); String
fotoname = "photo-" + n + ".jpg"; File file = new File(newDir,
fotoname); String s = file.getAbsolutePath();
System.err.print("******************" + s); if (file.exists())
file.delete(); try { FileOutputStream out = new
FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG,
90, out); out.flush(); out.close();
Toast.makeText(getApplicationContext(), "Saved to your folder ",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}

Using the method SVNClient.Diff Diff (SvnTarget target, SvnRevisionRange range, Stream results)

Given two different revisions need to get the differences between them, I intend to use the method duvuelve Diff but I anything as a result, it could be? Thanks.
My code is as follows
using (SvnClient client = new SvnClient())
using (MemoryStream result = new MemoryStream())
{
client.Authentication.DefaultCredentials = new NetworkCredential("asdf", "asdf/*");
try
{
//SvnUriTarget is a wrapper class for SVN repository URIs
SvnUriTarget target = new SvnUriTarget(textBox1.Text);
if (client.Diff(target, rango, result))
MessageBox.Show("Successfully para" + rango.ToString() + ".");
StreamReader strReader = new StreamReader(result);
string str = strReader.ReadToEnd();
}
}
The stream that is returned from the Diff() function is positioned at the end of the stream, so before creating your stream reader, you need to reposition it at the beginning of the stream:
result.Position = 0;
StreamReader strReader = new StreamReader(result);