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 :)
Related
There is an ASP.NET web page to encode some images and save them to a specified folder...
I want to call this page by JAVA URL method,
but I don't know how to use getOutputStream() method to save this encoded images....
The following is my unfinished code :
try {
String encodeImgUrl = "XXX.aspx";
InputStream is = null;
URL url = new URL(encodeImgUrl);
is = url.openStream();
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
// .... I don't know how to use connection.getOutputStream() to save this encoded images....
is.close();
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
I am using Apache Commons net FTPClient to login and read files from an FTP Server. I manage to login and I can see it logs in successfully, because it shows the working directory path in the header string. However it shows no files when I use listFiles(). (I have also tried using listDirectories() and listNames() but with no success)
Below is a snippet:
try {
client.connect(ftpHost);
} /*catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/ catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
String header ="";
InputStream stream=null;
BufferedReader reader=null;
try{
client.login(ftpUser, ftpPass);
client.changeWorkingDirectory(targetWorkingDir);
header = client.printWorkingDirectory();
//client.setFileType(FTP.BINARY_FILE_TYPE);
for(int i=0; i<client.listFiles().length;i++){
header+=client.listFiles()[i].getName() +"\n";
}
}
catch (IOException ex){
ex.printStackTrace();
header="ERROR 1: " + ex.getMessage();
for(int i=0;i<ex.getStackTrace().length;i++){
header += "\n" + ex.getStackTrace()[i];
}
}
catch(NullPointerException e){
header = "ERROR 2: "+ e.getMessage()+"\n";
for(int i=0;i<e.getStackTrace().length;i++){
header+= e.getStackTrace()[i] + "\n";
}
}
finally{
if(reader!=null){
try{reader.close();}catch(IOException e){e.printStackTrace();}
try{stream.close();}catch(IOException e){e.printStackTrace();}
}
}
I have also tried using something like this to read a file:
try {
stream = ftpClient.retrieveFileStream("klasa.csv");
reader = new BufferedReader(new InputStreamReader(stream));
header = reader.readLine();
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore){}
}
In both cases I'm pretty sure I'm at the right directory, and I make sure that my file is there via FileZilla, but the client can't seem to read any file.
Try to avoid calling listFiles() in the loop. Every call will perform the entire FTP LIST command sequence, so eventually, you will add unnecessary traffic to every call.
You can try to simplify your program first like this:
private static void ftpTest() {
FTPClient f = new FTPClient();
try {
f.connect("{UOUR FTP SERVER}");
f.login("{USER}", "{PASSWORD}");
FTPFile[] files = f.listFiles(".");
for (FTPFile fi: files) {
System.out.printf("f%s\n", fi.getName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
If this program will not give you the list of files in the root directory of your server, you can try to compare your FileZilla FTP options (PASSIVE/ACTIVE mode in particular): https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#enterLocalPassiveMode()
If it won't help you can try to sniff the network traffic using WireShark or tcpdump and compare the commands set to the FTP server.
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.
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
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.