Download a textfile with dropbox core api and android - java

i have a problem with download a textfile. I have no file contents after the dowload, the downloaded file is empty. Android and Core Api
#Override
protected Boolean doInBackground(Void... params) {
FileOutputStream outputStream = null;
try {
File fileDown = new File(LOCAL_PATH_DOWNLOAD);
outputStream = new FileOutputStream(fileDown);//
DropboxAPI.DropboxFileInfo info = mApi.getFile(DROPBOX_FILE_DIR_DOWNLOAD, null, outputStream, null);
return false;
} catch (Exception e) {
System.out.println("Something went wrong: " + e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
}
return false;
}
What do i wrong? Thanks for help

i use above code to do this
File file= new File("/sdcard/New_csv_file.csv");
OutputStream out= null;
boolean result=false;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
DropboxFileInfo info = mApi.getFile("/photos/New_csv_file.csv", null, out, null);
Log.i("DbExampleLog", "The file's rev is: " + info.getMetadata().rev);
Intent JumpToParseCSV=new Intent(context,ParseCSV.class);
JumpToParseCSV.putExtra("FileName", file.getAbsolutePath());
Log.i("path", "FileName"+ file.getAbsolutePath());
((Activity) context).finish();
context.startActivity(JumpToParseCSV);
result=true;
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while downloading.");
file.delete();
result=false;
}
return result;

Related

File is being recreated even though it already exists

How does this code delete the file I had and makes a new one??
public void actualizaJTextArea(String cliente){
mensagens.setText("");
Scanner scanner = null;
File file = createFile(cliente + "chatswith.txt");
try {
scanner = new Scanner(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(...)
scanner.close();
}
public static File createFile(String s){
File file = new File(s);
if(!file.exists()){
try {
boolean b = file.createNewFile();
System.out.println(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
Does the method createNewFile() do this?
Thanks and I'm sorry if this has been asked before I just can't find it.
EDIT
I am also using createFile() in here to write in it but the use is the same so i guess that can't be it:
public void recebeMensagem(boolean b){
while(true){
Mensagem m = null;
try {
m = (Mensagem)input.readObject();
System.out.println("Mensagem Recebida:"+m);
} catch (ClassNotFoundException e){
} catch (IOException e) {
try {
input.close();
System.out.println("Server desligou...");
break;
} catch (IOException e1) {
}
}
if(m != null){
for(Mensagens mensagens:v){
for(String string: m.getReceivers()){
if (mensagens.getCliente().equals(m.getAuthor()) && mensagens.getContacto().equals(string)){
mensagens.actualizaJTextArea(cliente);
}
}
}
for(String Str :m.getReceivers()){
PrintWriter p = null;
File file = Mensagens.createFile(cliente + "chatswith.txt");
try {
p = new PrintWriter(new FileWriter(file));
p.append(m.getAuthor()+"</<"+Str+"</<"+m.getText()+"\n");
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
createNewFile() is atomic and it will not delete the file if it is present. Please look at the boolean output, it should be false if your file exists already.
EDIT
add append parameter to FileWriter. It is overwriting every time.
FROM
p = new PrintWriter(new FileWriter(file));
TO
p = new PrintWriter(new FileWriter(file,true));

Apache Tika - Incorrect MIME (content type) detection

I'm trying to detect a file content type passed to a web service into the SOAP envelop.
This file can be indicated in two ways :
from its url,
from its contain (base64 compressed data).
At this point, I'm able to translate this file into a stream buffer.
But, all my tries to get its content type failed.
The content type is detected if the file extension is indicated otherwise the content is always detected as "plain/text".
Bellow is my class code :
class MetadataAnalyser {
private InputStream _is;
private File _file;
private void initializeAttributes() {
_is = null;
_file= null;
}
private void createTemporaryFile(byte[] pData) {
FileOutputStream fos = null;
try {
_file = File.createTempFile(
UUID.randomUUID().toString().replace("-", ""),
null,
new File("C:\\Users\\Florent\\Documents\\NetBeansProjects\\ServiceEdition\\tmp"));
} catch (IOException e) {
e.printStackTrace();
}
try {
fos = new FileOutputStream(_file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(pData);
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
_file.deleteOnExit();
}
public MetadataAnalyser(byte[] pData) {
initializeAttributes();
_is = new ByteArrayInputStream(pData);
createTemporaryFile(pData);
}
public MetadataAnalyser(InputStream pIs) {
initializeAttributes();
_is = pIs;
_file = null;
}
public MetadataAnalyser(File pFile) {
initializeAttributes();
try {
_file = pFile;
_is = new FileInputStream(_file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public MetadataAnalyser(String pFile) {
initializeAttributes();
try {
_file = new File(pFile);
if (_file.exists()) {
_is = new FileInputStream(_file);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getContentType() {
AutoDetectParser parser = null;
Metadata metadata = null;
InputStream is = null;
String mimeType = null;
parser = new AutoDetectParser();
parser.setParsers(new HashMap<MediaType, Parser>());
metadata = new Metadata();
if(_file != null) {
metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, _file.getName());
}
try {
is = new FileInputStream(_file);
parser.parse(is, new DefaultHandler(), metadata, new ParseContext());
mimeType = metadata.get(HttpHeaders.CONTENT_TYPE);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
} finally {
return mimeType;
}
}
}
So, how to detect the MIME type even if the file extension is unknown ?
I don't think you can detect the mime type without extension , you would need to know which system is writing the file and what kind of file is expected to be there and based on that you need to set the MIME type(I guess you are using it in your response).
You need to make sure the content is decoded before being sent to Tika and no, the extension is absolutely not needed, the detection happens via a well understood mime magic process described here: https://tika.apache.org/1.1/detection.html

File writer not typing in file (Java)

I made a program to produce a file with numbers in it
But the program is not typing any thing in the file it created!
This is the code:
private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
ModFile=new File(NameText.getText() + ".mod");
FileWriter writer = null;
try {
writer = new FileWriter(ModFile);
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
if(!ModFile.exists()){
try {
ModFile.createNewFile();
System.out.println("Mod file has been created to the current directory");
writer.write(CodesBox.getText());
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When i create a random file, i don't see any thing when i open it!
Please help
Thanks Amir for helping but i noticed i should use FileOutputStream and DataOutputStream...
So, i need help again cause the same problem appeared :(
File ModFile =new File(NameText.getText() + ".mod");
try {
FileOutputStream fos = new FileOutputStream(ModFile);
DataOutputStream dos = new DataOutputStream(fos);
int i = Integer.parseInt(CodesBox.getText());
dos.writeInt(i);
// and other processing
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try{
dos.close();
} catch(IOException e) {
e.printStackTrace();
}
}
NetBeans said they cannot find the symbol dos at (dos.close();)
Please help me here again
You have to check that file name is present in NameText.getText().
You dont need to create file, if file dont exist FileWriter will create it self.
You should Close file after processing
private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
//check before file name is nt null
File ModFile =new File("somefile" + ".mod");
FileWriter writer = null;
try {
writer = new FileWriter(ModFile);
writer.write("test..................");
// and other processing
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
to use FileOutputStream and write byte array follow the following code
private static void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
//check before file name is nt null
File ModFile =new File("somefile" + ".mod");
FileOutputStream writer = null;
String toProcess = "00D0C0DE00D0C0DE F000000000000000";
try {
writer = new FileOutputStream(ModFile);
writer.write(toProcess.getBytes(),0,toProcess.getBytes().length);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to overwrite a file if it already exists in dropbox?

I am uploading a file in dropbox by this method:
public void upload() {
FileInputStream inputStream = null;
try {
File file = new File(Environment.getExternalStorageDirectory()
.toString() + "/write.txt");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/write.txt", inputStream,
file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
but when already this file exists in the folder then the file get renamed to write(1).txt
but I want that if the file already exists in the dropbox share folder then it will be replaced. What should I do now?
You can use mDBApi.putFileOverwrite instead of mDBApi.putFile

Unable to Upload file on FTP Server in android

I am trying to Upload file like this
try {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString
FTPClient ftpClient = new FTPClient();
ftpClient.connect("xxx.xxx.xx.xx");
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
{
boolean status=ftpClient.login("username", "password");
Log.d(TAG, "login status=="+status);
status=ftpClient.changeWorkingDirectory("New directory");
Log.d(TAG, "changeWorkingDirectory status=="+status);
status=ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
Log.d(TAG, "setFileType status=="+status);
ftpClient.enterLocalPassiveMode();
String srcFilePath=extStorageDirectory + "/AA.txt";
FileInputStream srcFileStream = new FileInputStream(new File(srcFilePath));
status=ftpClient.storeFile("AA.txt", srcFileStream);
Log.d(TAG, "upload status=="+status);
ftpClient.logout();
ftpClient.disconnect();
}
else
{
Log.d(TAG, "connectfail");
}
} catch (SocketException e) {
Log.d(TAG, "SocketException status=="+e.toString());
e.printStackTrace();
} catch (FileNotFoundException e) {
Log.d(TAG, "FileNotFoundException status=="+e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "IOException status=="+e.toString());
e.printStackTrace();
}
below is my logcat status
07-11 12:24:43.359: D/FTPDownloadDroid(10647): <!>com.ss.dr 138<!> login status==true
07-11 12:24:48.379: D/FTPDownloadDroid(10647): <!>com.ss.dr 141<!> changeWorkingDirectory status==true
07-11 12:24:48.859: D/FTPDownloadDroid(10647): <!>com.ss.dr 143<!> setFileType status==tr
07-11 12:24:54.359: D/FTPDownloadDroid(10647): <!>com.ss.dr 150<!> upload status==false
I want to Upload file on "New Directory" folder and file name AA.txt ** but it is giving Upload status false.**
Is the problem in server or in my Code???
Please help!!!!!!!!!
Thanks in advance
Try my code below, i used this to upload and download a song on the server. I am using the Apache's common lib.
Please make the changes for the directories and file name in the below code.
UPLOAD:
public void goforIt(){
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("192.168.2.57");
if (con.login("Administrator", "KUjWbk"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a";
FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/vivekm4a.m4a", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
DOWNLOAD:
public void goforIt(){
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("192.168.2.57");
if (con.login("Administrator", "KUjWbk"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a";
OutputStream out = new FileOutputStream(new File(data));
boolean result = con.retrieveFile("vivekm4a.m4a", out);
out.close();
if (result) Log.v("download result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
Log.v("download result","failed");
e.printStackTrace();
}
}

Categories

Resources