public class FtpDownloadDemo {
public static void Connection(String filename) {
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
client.connect("ftp.domain.com");
client.login("admin", "secret");
//
// The remote filename to be downloaded.
//
ftpClient.setFileType(FTP.IMAGE_FILE_TYPE);
fos = new FileOutputStream(filename);
//
// Download file from FTP server
//
client.retrieveFile("/" + filename, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I am using this code to download some image file. but at fos = new FileOutputStream(filename); getting file.jpeg is readonly file exception. i am using commons.net jar file for ftp connection. please help me where i am wrong.
I supplied the host, username and password when creating the class and then called this to download the file. Those guys were right it probably was trying to write to the root or something. I have been using commons-net-2.2.jar for this client.
public void GetFileFTP(String srcFileSpec, String destpath, String destname) {
File pathSpec = new File(destpath);
FTPClient client = new FTPClient();
BufferedOutputStream fos = null;
try {
client.connect(mhost);
client.login(muser, mpass);
client.enterLocalPassiveMode(); // important!
client.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
fos = new BufferedOutputStream(
new FileOutputStream(pathSpec.toString()+"/"+destname));
client.retrieveFile(srcFileSpec, fos);
}//try
catch (IOException e) {
Log.e("FTP", "Error Getting File");
e.printStackTrace();
}//catch
finally {
try {
if (fos != null) fos.close();
client.disconnect();
}//try
catch (IOException e) {
Log.e("FTP", "Disconnect Error");
e.printStackTrace();
}//catch
}//finally
Log.v("FTP", "Done");
}//getfileFTP
Hope this helps.
phavens
Related
url = "http://r8---sn-03guxaxjvh-3c2r.googlevideo.com/videoplayback?sparams=dur%2Cei%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Csource%2Cexpire&mn=sn-03guxaxjvh-3c2r&ip=212.113.45.145&source=youtube&mm=31&mv=m&mime=video%2Fmp4&mt=1505092537&ipbits=0&initcwndbps=685000&dur=2223.728&id=o-AM9pUI9o5NsL8P-jGi5-w17xJOo-VVQ-TrWlMZaV17cp&key=yt6&lmt=1499875418101464&signature=4AACC08B22F2F1F343F5A044188CD751A6AD2F08.A7BA661DDC07639A7E414169226A35A700888AF3&ms=au&ei=HOS1WezYFZfq7gT40rnoAw&itag=22&pl=22&expire=1505114236&ratebypass=yes&title=Gothic+Rock+-+Dark+Music";
streamPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
streamPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
streamPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
streamPlayer.start();`
my question is how to store on a device my streamPlayer object?
Try this
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new
FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.
I have to open a file that in the /res/raw/ folder, but it seems that android, doesn't recognize the path.
Here is my code:
public static void openRec()
{
//this is the wav file that I have to analyze
File file = new File("/res/raw/chirp.wav");
try {
FileInputStream in = new FileInputStream(file);
chirp = new byte[(int) file.length()];
in.read(chirp);
Log.d("xxx", "" + chirp.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT:
I have another method openRec in which, the path is passed as argument:
public static void openRec(String path) {
File file = new File(path);
try {
FileInputStream in = new FileInputStream(file);
recording = new byte[(int) file.length()];
in.read(recording);
Log.d("xxx", "" + recording.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I would a method that do the same thing but with the ffile in /res/raw. How do I that?
Use in this manner
public static void openRec()
{
//this is the wav file that I have to analyze
try {
InputStream in = getResources().openRawResource(R.raw.chirp);
chirp = new byte[(int) file.length()];
in.read(chirp);
Log.d("xxx", "" + chirp.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have an application consist on reading AND saving an xml file and to write it if internet connection is available,else it will read the file already saved on the terminal.
WriteFeed function:
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
WriteFeed function:
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
I have enough diskSpace ,sometimes i get "MemoryCach will use up to 16 Mb" ,always i get "Not enough disk space,will not index" and "FeatureCode > cannot open file"
whats wrong in my app?
I used following code for downloading XML file from ftp to android phone memory using that i able to connect ftp but while retrieving XML to local memory it is giving following exception 07-19 15:01:03.721: DEBUG/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol
please help somebody thank you,
Java class
private void fnfileDownloadBuf()
{
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
//client.connect("ftp://ftp.qualityinaction.net/QIA/Questions/Airlines/");
client.connect("ftp.qualityinaction.net");
client.login("qualityinaction.net","password");
client.setFileType(FTP.BINARY_FILE_TYPE);
//
// The remote filename to be downloaded.
//
// String filename = "/QIA/Questions/Airlines/index.xml";
String filename = getFilesDir().getAbsolutePath()+ File.separator + "/index.xml";
// String filename = "/QIA/Questions/Airlines/index.xml";
File file = new File(filename);
fos = new FileOutputStream(file);
//
// Download file from FTP server
//
//client.retrieveFile("/" + filename, fos);
client.retrieveFile("/QIA/Questions/Airlines/index.xml;type=i", fos);
// client.retrieveFile( getFilesDir().getAbsolutePath()+ File.separator + "/index.xml", fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
manifest XML file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Exception
exception 07-19 15:01:03.721: DEBUG/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol
for that you have to use passive mode corrected code as shown below..
** Java Code **
FTPClient ObjFtpCon = new FTPClient();
try
{
ObjFtpCon.connect(strIp);
if (ObjFtpCon.login(strFtpUser, strFtpPwd))
{
ObjFtpCon.enterLocalPassiveMode(); // important!
ObjFtpCon.cwd("/QIA/Questions/Hotel/");
String[] strArrQuesFiles=ObjFtpCon.listNames();
int intcnt=0;
boolean blnresult = false;
File objfile=new File(getFilesDir().getAbsolutePath()+ "/Questions");
if(!objfile.exists())objfile.mkdirs();
objfile=null;
for(intcnt=0;intcnt<strArrQuesFiles.length;intcnt++)
{
objfile=new File(getFilesDir().getAbsolutePath()+ File.separator + "/Questions/" + strArrQuesFiles[intcnt]);
objfile.createNewFile();
//ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
FileOutputStream objFos=new FileOutputStream(objfile);
blnresult=ObjFtpCon.retrieveFile(strArrQuesFiles[intcnt] , objFos);
objFos.close();
}
// boolean result = con.storeFile("/QIA/Response/test/Responses.xml", in);
if (blnresult) dlgAlert.setMessage("Questions Are Successfully Downloaded").create().show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
ObjFtpCon.logout();
ObjFtpCon.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
}
}