使用非活动类写入文件

时间:2014-07-16 11:40:06

标签: java android

WithClassesMainActivity:

        final Button b1= (Button) findViewById(R.id.button1);
        final Button b2= (Button) findViewById(R.id.button2);
        final Button b3= (Button) findViewById(R.id.button3);

        final StoringClas sc=new StoringClas();

        b1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String array1[]=new String[5];
                 array1[0]="a";array1[1]="b";array1[2]="y";array1[3]="g";
                 sc.writeToFile(array1);
            }
        });
       b2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String[] ty =new String[5];
             ty=    sc.readFromFile();
            b2.setText("ff"+ty[0]+ty[1]+ty[2]+ty[3]);
            }
        });
       b3.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

        String fs[]=new String[4];
        try{
            FileInputStream fIn = openFileInput("passd.txt");
            InputStreamReader isr = new InputStreamReader(fIn);

            /* Prepare a char-Array that will
             * hold the chars we read back in. */
            char[] inputBuffer = new char[6];

            // Fill the Buffer with data from the file

            isr.read(inputBuffer);

            // Transform the chars to a String

    String str=new String(inputBuffer);

    fs[0]=str.substring(0,1);
    fs[1]=str.substring(1,2);
    fs[2]=str.substring(2,3);
    fs[3]=str.substring(3,4);

    b3.setText("g"+fs[0]+fs[1]+fs[2]+fs[3]);

        } catch (IOException ioe) 
          {ioe.printStackTrace();
          }}
});

存储类:

public class StoringClas extends Activity {


    @SuppressLint("WorldReadableFiles")
    @SuppressWarnings("deprecation")
    public void writeToFile(String[] args){
         try { 
           FileOutputStream fOut = openFileOutput("passd.txt",MODE_WORLD_READABLE);

                OutputStreamWriter osw = new OutputStreamWriter(fOut); 

                // Write the string to the file

                for(int i=0;i<=3;i++){
                 osw.write(args[i]);
                }

                //ensure that everything is
                 // really written out and close 
                osw.flush();
                osw.close();}
            catch(Exception Ex){}


   }

        public String[] readFromFile(){

        String fs[]=new String[4];
        try{
            FileInputStream fIn = openFileInput("passd.txt");
            InputStreamReader isr = new InputStreamReader(fIn);

            /* Prepare a char-Array that will
             * hold the chars we read back in. */
            char[] inputBuffer = new char[6];

            // Fill the Buffer with data from the file

            isr.read(inputBuffer);

            // Transform the chars to a String

    String str=new String(inputBuffer);

    fs[0]=str.substring(0,1);
    fs[1]=str.substring(1,2);
    fs[2]=str.substring(2,3);
    fs[3]=str.substring(3,4);
    } catch (IOException ioe) 
          {ioe.printStackTrace();
          }
        return fs;
        }}

logcat的:

try{07-16 17:21:19.349: I/Adreno-EGL(4013): <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: 
AU_LINUX_ANDROID_LNX.LA.3.5.1_RB1.04.04.02.048.018_msm8610_LNX.LA.3.5.1_RB1__release_AU ()
07-16 17:21:19.349: I/Adreno-EGL(4013): OpenGL ES Shader Compiler Version: E031.24.00.08
07-16 17:21:19.349: I/Adreno-EGL(4013): Build Date: 03/07/14 Fri
07-16 17:21:19.349: I/Adreno-EGL(4013): Local Branch: 
07-16 17:21:19.349: I/Adreno-EGL(4013): Remote Branch: quic/LNX.LA.3.5.1_RB1.1
07-16 17:21:19.349: I/Adreno-EGL(4013): Local Patches: NONE
07-16 17:21:19.349: I/Adreno-EGL(4013): Reconstruct Branch: AU_LINUX_ANDROID_LNX.LA.3.5.1_RB1.04.04.02.048.018 
+ f2fd134 +  NOTHING
07-16 17:21:19.399: D/OpenGLRenderer(4013): Enabling debug mode 0
07-16 17:21:21.251: D/AndroidRuntime(4013): Shutting down VM
07-16 17:21:21.251: W/dalvikvm(4013): threadid=1: thread exiting with uncaught exception (group=0x4165fd40)
07-16 17:21:21.254: E/AndroidRuntime(4013): FATAL EXCEPTION: main
07-16 17:21:21.254: E/AndroidRuntime(4013): Process: com.example.withclasses, PID: 4013
07-16 17:21:21.254: E/AndroidRuntime(4013): java.lang.NullPointerException
07-16 17:21:21.254: E/AndroidRuntime(4013):     at 
android.content.ContextWrapper.openFileInput(ContextWrapper.java:179)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at 
com.example.withclasses.StoringClas.readFromFile(StoringClas.java:46)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at 
com.example.withclasses.WithClassesMainActivity$2.onClick(WithClassesMainActivity.java:41)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at android.view.View.performClick(View.java:4456)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at android.view.View$PerformClick.run(View.java:18465)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at android.os.Handler.handleCallback(Handler.java:733)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at android.os.Handler.dispatchMessage(Handler.java:95)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at android.os.Looper.loop(Looper.java:136)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at android.app.ActivityThread.main(ActivityThread.java:5086)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at java.lang.reflect.Method.invokeNative(Native Method)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at java.lang.reflect.Method.invoke(Method.java:515)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at 
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
07-16 17:21:21.254: E/AndroidRuntime(4013):     at dalvik.system.NativeStart.main(Native Method)}

首先,我点击button1写入文件。 但是,当我点击button2应用程序停止工作。 单击按钮3显示文件中没有存储任何内容。 代码有什么问题? 在此先感谢.....

1 个答案:

答案 0 :(得分:3)

您应该将Context(Activity扩展)传递给Util类中的静态方法,从而实现Write a File和Activity本身的干净解耦。

public class FileHelper {

    public static void writeFile(Context context, ...) {}
}