Android FTP上传错误

时间:2015-08-17 08:15:14

标签: android ftp

嗨,这是我的第一篇文章,很抱歉,如果我犯了任何错误。

这是我的问题:我正在编写一个应用程序,当您单击一个按钮然后将其发送到FTP服务器时,如果您单击另一个按钮,该应用程序应将今天的日期保存在txt文件中。我使用Apache commons库进行FTP连接。

这是我的MainActivity:

package com.example.timestamp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import it.sauronsoftware.ftp4j.FTPClient;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getName();
    final File log = new File("TimeStampLog.txt");
    final String SERVER = "***************";
    final String USERNAME = "**************";
    final String PASSWORD = "*************";
    final int PORT = 21;
    final TextView tv = (TextView) findViewById(R.id.textView1);
    Button save = (Button) findViewById(R.id.save);
    Button send = (Button) findViewById(R.id.send);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String date = DateFormat.getDateTimeInstance().format(new Date());
                tv.setText(date);
                StringBuilder sb = new StringBuilder();
                sb.append(date);
                sb.append("\r\n");
                sb.append(readFromFile());
                writeToFile(sb.toString());
            }
        });

        send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                uploadFile(log);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void uploadFile(File fileName) {

        FTPClient client = new FTPClient();

        try {

            client.connect(SERVER, 21);
            client.login(USERNAME, PASSWORD);
            client.setType(FTPClient.TYPE_BINARY);

            client.upload(log);

        } catch (Exception e) {
            e.printStackTrace();
            try {
                client.disconnect(true);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

    }

    private void writeToFile(String data) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                    openFileOutput(log.getName(), Context.MODE_PRIVATE));
            outputStreamWriter.write(data);
            outputStreamWriter.flush();
            outputStreamWriter.close();
        } catch (IOException e) {
            Log.e(TAG, "File write failed: " + e.toString());
        }

    }

    private String readFromFile() {

        String ret = "";

        try {
            InputStream inputStream = openFileInput(log.getName());

            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);
                    stringBuilder.append("\r\n");
                }

                inputStream.close();
                ret = stringBuilder.toString();
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e(TAG, "Can not read file: " + e.toString());
        }

        return ret;
    }
}

我的XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.timestamp.MainActivity" >

<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="60dp"
        android:text="@string/save" />

    <Button
        android:id="@+id/send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/save"
        android:layout_alignBottom="@+id/save"
        android:layout_alignParentRight="true"
        android:text="@string/send" />

</RelativeLayout>

这是LogCat输出:

08-14 13:51:45.919: E/AndroidRuntime(14598): FATAL EXCEPTION: main
08-14 13:51:45.919: E/AndroidRuntime(14598): Process: com.example.timestamp, PID: 14598
08-14 13:51:45.919: E/AndroidRuntime(14598): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.timestamp/com.example.timestamp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread.access$800(ActivityThread.java:144)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.os.Handler.dispatchMessage(Handler.java:102)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.os.Looper.loop(Looper.java:135)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread.main(ActivityThread.java:5221)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at java.lang.reflect.Method.invoke(Native Method)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at java.lang.reflect.Method.invoke(Method.java:372)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
08-14 13:51:45.919: E/AndroidRuntime(14598): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.Activity.findViewById(Activity.java:2071)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at com.example.timestamp.MainActivity.<init>(MainActivity.java:33)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at java.lang.reflect.Constructor.newInstance(Native Method)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at java.lang.Class.newInstance(Class.java:1572)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
08-14 13:51:45.919: E/AndroidRuntime(14598):    ... 10 more

是的我将互联网添加到使用权限

我认为问题可能是我需要另一个用于FTP实现的线程,我尝试使用AsyncTask和Handler,但我一直遇到同样的错误。

1 个答案:

答案 0 :(得分:0)

从LogCat输出我可以看到你得到NullPointerException,因为你已经初始化了我们可以声明任何变量的Button和TextView。

OnCreate()方法中调用 setContentView(R.layout.activity_main); 之前,您已初始化并充气所有按钮和TextView。您已在OnCreate方法中移动代码,然后尝试上传文件。

您可以尝试以下代码:

package com.example.timestamp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import it.sauronsoftware.ftp4j.FTPClient;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getName();
    final File log = new File("TimeStampLog.txt");
    final String SERVER = "***************";
    final String USERNAME = "**************";
    final String PASSWORD = "*************";
    final int PORT = 21;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView tv = (TextView) findViewById(R.id.textView1);
        Button save = (Button) findViewById(R.id.save);
        Button send = (Button) findViewById(R.id.send);
        save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String date = DateFormat.getDateTimeInstance().format(new Date());
                tv.setText(date);
                StringBuilder sb = new StringBuilder();
                sb.append(date);
                sb.append("\r\n");
                sb.append(readFromFile());
                writeToFile(sb.toString());
            }
        });

        send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                uploadFile(log);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void uploadFile(File fileName) {

        FTPClient client = new FTPClient();

        try {

            client.connect(SERVER, 21);
            client.login(USERNAME, PASSWORD);
            client.setType(FTPClient.TYPE_BINARY);

            client.upload(log);

        } catch (Exception e) {
            e.printStackTrace();
            try {
                client.disconnect(true);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

    }

    private void writeToFile(String data) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                    openFileOutput(log.getName(), Context.MODE_PRIVATE));
            outputStreamWriter.write(data);
            outputStreamWriter.flush();
            outputStreamWriter.close();
        } catch (IOException e) {
            Log.e(TAG, "File write failed: " + e.toString());
        }

    }

    private String readFromFile() {

        String ret = "";

        try {
            InputStream inputStream = openFileInput(log.getName());

            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);
                    stringBuilder.append("\r\n");
                }

                inputStream.close();
                ret = stringBuilder.toString();
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e(TAG, "Can not read file: " + e.toString());
        }

        return ret;
    }
}

我希望它有所帮助!