error: URL can not open stream - java

When I use openStream() to parse XML from a web service, I get the error:
Can not open stream
I've checked the URL and it's still working.
URL url = new URL("http://uitbookshop.php0h.com/PHPService/findbyname.php?name=thu");
Log.d("search", "getXML::url "+url.toString());
InputStream iS;
try {
iS = url.openStream();
doc=db.parse(new InputSource(new InputStreamReader(iS, Charset.forName("utf-8"))));
} catch (IOException e) {
Log.e("search", "Can not open stream");
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Have you given appropriate Permissions?
make sure you have following permission added to the manifest
android.permission.INTERNET

Related

JAVA Android , acces to a file with getRessourceAsStream

i would like to handle a a properties file in my android app. The Properties-File is in the main-Folder, in the folder with the other jar-files. I know, that´s not best.
Code:
InputStream propStream=MainActivity.class.getResourceAsStream("data.properties");
Log.d("propStreamOutput",propStream.toString());
File data = new File(propStream.toString());
Reader reader;
try {
reader = new FileReader(data);
dataProp = new Properties();
dataProp.load( reader );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
so, the log at line 2 says:
libcore.net.url.JarURLConnectionImpl$JarURLConnectionInputStream#421302e8
in this form logcat calls a System.err :
java.io.FileNotFoundException/libcore.net.url.JarURLConnectionImpl$JarURLConnectionInputStream#42097218: open failed: ENOENT (No such file or directory)
but when I comment like this:
InputStream propStream=MainActivity.class.getResourceAsStream("data.properties");
Log.d("propStreamOutput",propStream.toString());
File data = new File(propStream.toString());
// Reader reader;
// try {
// reader = new FileReader(data);
// dataProp = new Properties();
// dataProp.load( reader );
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
then there is no system.err ! Of course the log call at line 2 says the same.
If you really wanna use the getResourceAsStream() then you have to put the file on the "src" folder, together with your .java files.
This is usually the way for standard Java applications, but on Android the most usual way to perform such things is to put the file in the 'assets' folder, via AssetsManager, which is accessible from your Activity or any Context. like shown below:
InputStream is = null;
try {
is = context.getAssets().open("data.properties");
} catch (final IOException e) {
e.printStackTrace();
} finally {
closeStreamGracefully(is);
}
getRessourceAsStream return an InputStream. When you call toString on this it will return a string representation of the object. Then when you create your data file and try to read it will try to open a file like #sdqzeffdfsf. If you whant to read the properties from this file use Properties
Properties properties = new Properties();
properties.load(propStream);
This is for standard java. However in android you usualy use AssetManager

Calling php script from java - Android

I have the following copyfile.php file inside my main directory with the below code :
<?php
copy("dir1/test.php","dir2/test.php");
?>
Basically just moving a file from dir1 to dir2 (both the directories are already created and are present in my main directory)
I am using the following java code to call my copyfile.php
try {
URL url;
url = new URL( "http://www.xyz.com/copyfile.php" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
// do something with the data here
}else{
InputStream err = conn.getErrorStream();
// err may have useful information.. but could be null see javadocs for more information
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The program runs without any errors but the file is not being copied.
But if I paste the above url (http://www.xyz.com/copyfile.php) in the browser it works fine the file gets copied to dir2. Am I doing something wrong? Please help. Thanks in advance :)

Android: Dowloaded files got deleted when the app restarts

I download audio files from server using
try {
// URL url = new URL("http://commonsware.com/misc/test2.3gp");
URL url = new URL("http://192.168.0.2/supplications/"+fileName);
//URL url = new URL("http://www.msoftech.com/supplications/android/"+fileName);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
Log.v("log_tag", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d("log_tag", "Error: " + e);
}
Log.v("log_tag", "Check: " +cd2);
Here PATH = "/data/data/packagename/sounds/filename
It works fine, audio file downloaded and played successfully, but my problem is when I click the home button and then restart the app means the folder with the downloaded audio was not found, ie, when exit the app means all the downloaded audios were deleted automatically. It throws the exception file not found.
For playing the downloaded file I used the code as below,
public void audioPlayer(String path, String fileName) throw FileNotFoundException
{
//set up MediaPlayer
FileInputStream fileInputStream = new FileInputStream(PATH+"/"+fileName);
//String command = "chmod 666 " + recordFile.toString();
try {
mp.setDataSource(fileInputStream.getFD());
// mp.setDataSource(path+"/"+filename.mp3);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
whats the problem with it what I have to do for saving the audio file permenantly.
There is nothing problem in your code it is a file permission issue.
When you download file into internal file system under application package a security is assigned to it like "-rw------" this means your file is accessible for the same application only.As android is on Linux based so every file have some permission.
Your file would be there but not accessible to other application like media player etc, so these application throws error like file not found.(you can check though DDMS tool).
Just change the file path to external drive.
Accept the answer if it is helpful.

Android loading from file Error

I am getting the occassional error message when I try to read a serialized object from a file. It works fine 9 times out of 10, but for some reason I get lots of these error message sin the catlog:
06-01 23:57:50.824: ERROR/MemoryFile(16077): MemoryFile.finalize() called while ashmem
still open
and
06-01 23:57:57.664: ERROR/MemoryFile(16077): java.io.IOException: munmap failed
The second message comes with no indication where the exception is caused. (Clearly when I'm loading the file, but I already have a try/catch around it.)
My loadfile method looks like this:
public TGame loadSavedGame(){
TGame g=null;
InputStream instream = null;
BufferedReader br=null;
InputStreamReader inputreader=null;
try {
File sdCard = Environment.getExternalStorageDirectory();
instream = new
FileInputStream(sdCard.getAbsolutePath()+"/egyptica/serializationtest");
// inputreader = new InputStreamReader(instream);
// br= new BufferedReader(inputreader);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return g;
} catch (ClassNotFoundException ex) {
// TODO Auto-generated catch block
android.util.Log.e("DESERIALIZATION FAILED (CLASS NOT
FOUND):"+ex.getMessage(), "ex");
ex.printStackTrace();
return null;
}
} catch (StreamCorruptedException ex) {
android.util.Log.e("DESERIALIZATION FAILED (CORRUPT):"+ex.getMessage(),
"ex");
// TODO Auto-generated catch block
ex.printStackTrace();
return null;
} catch (IOException ex) {
android.util.Log.e("DESERIALIZATION FAILED (IO
EXCEPTION):"+ex.getMessage(), "ex");
// TODO Auto-generated catch block
ex.printStackTrace();
return null;
}
}
One possibility I have thought of is using a BufferedReader to rea the file. However I'm not sure how to go about doing this. Any help would be appreciated.
Try to put finally block after try and put there closing statements for your streams and also useful thing is to use:
FileInputStream.getFD().sync();
It makes sure that file really received your close/flush

Transfering text data to a web server using Java

I'm trying to write to a text file on my web server using HttpURLConnection.getOutputStream(). I have tried this on two different servers without success.
I have added a FileWriter to test the InputStream, and that file is created on a local directory correctly, but nothing is showing up on the in the web server directory, even with all password protection off.
Any help would be greatly appreciated.
URL url;
try {
url = new URL("http://www.myWebsite.com/myFile.txt");
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
OutputStream in = new BufferedOutputStream(urlConnection.getOutputStream());
InputStream fin1;
try {
fin1 = new FileInputStream(Environment.getExternalStorageDirectory() + "/fileToRead.txt");
FileWriter fWriter = new FileWriter(Environment.getExternalStorageDirectory() + "/fileToWrite.txt");
int data = fin1.read();
while(data != -1) {
fWriter.write(data);
in.write(data);
data = fin1.read();
}
fWriter.flush();
fWriter.close();
fin1.close();
in.flush();
in.close();
} catch (FileNotFoundException e31) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
} catch (IOException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
} catch (MalformedURLException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
You have to call getInputStream() on the urlConnection in order to get the output stream to flush out the socket to the remote server.
See the discussion here: Why do you have to call URLConnection#getInputStream to be able to write out to URLConnection#getOutputStream?
You are catching the IOException (Right after the IOException) but are not doing anything with it. At least print the stack trace.
You can also use Apache's Http Client http://hc.apache.org/httpcomponents-client-ga/index.html
Much easier than getting URLConnection to work.

Categories

Resources