尝试在Android中编写文件时始终获取nullpointerexceptions

时间:2016-02-05 09:11:00

标签: java android

我正在尝试将我的设置保存在文件中,但总是在写入文件时,我得到NullPointerException

02-05 09:54:21.021 4102-4102/? I/art: Not late-enabling -Xcheck:jni (already on)
02-05 09:54:21.092 4102-4102/com.example.andy.newshit W/System: ClassLoader referenced unknown path: /data/app/com.example.andy.newshit-1/lib/x86_64
02-05 09:54:22.588 4102-4180/com.example.andy.newshit D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-05 09:54:22.618 4102-4180/com.example.andy.newshit I/OpenGLRenderer: Initialized EGL, version 1.4
02-05 09:54:22.630 4102-4180/com.example.andy.newshit W/EGL_emulation: eglSurfaceAttrib not implemented
02-05 09:54:22.630 4102-4180/com.example.andy.newshit W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f76333968c0, error=EGL_SUCCESS
02-05 09:54:26.746 4102-4102/com.example.andy.newshit W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
02-05 09:54:26.795 4102-4180/com.example.andy.newshit W/EGL_emulation: eglSurfaceAttrib not implemented
02-05 09:54:26.795 4102-4180/com.example.andy.newshit W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f7633396c80, error=EGL_SUCCESS
02-05 09:54:28.031 4102-4180/com.example.andy.newshit W/EGL_emulation: eglSurfaceAttrib not implemented
02-05 09:54:28.031 4102-4180/com.example.andy.newshit W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f7626d5a640, error=EGL_SUCCESS
02-05 09:54:28.142 4102-4180/com.example.andy.newshit E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f7637d5a780
02-05 09:54:28.145 4102-4180/com.example.andy.newshit E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f7637d59e50
02-05 09:54:28.146 4102-4180/com.example.andy.newshit D/OpenGLRenderer: endAllStagingAnimators on 0x7f7626dba000 (ListPopupWindow$DropDownListView) with handle 0x7f7626edad00
02-05 09:54:32.604 4102-4102/com.example.andy.newshit D/AndroidRuntime: Shutting down VM
02-05 09:54:32.604 4102-4102/com.example.andy.newshit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.andy.newshit, PID: 4102 java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:183)
at com.example.andy.newshit.Filehandling.writeFile(Filehandling.java:20)
at com.example.andy.newshit.IPandPort.setIP(IPandPort.java:45)
at com.example.andy.newshit.SettingsActivity$1.onClick(SettingsActivity.java:29)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

这是我必须处理文件的类

package com.example.andy.newshit;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * Created by buddy on 05.02.16.
 */
public class Filehandling extends AppCompatActivity{

    public void writeFile(String Filename, String Text) throws IOException {
        FileOutputStream fos = openFileOutput(Filename, Context.MODE_PRIVATE);
        fos.write(Text.getBytes());
        fos.close();
    }

    public void readFile(String File) throws IOException {
        try {
            BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput(File)));
            String inputString;
            StringBuffer stringBuffer = new StringBuffer();
            inputString = inputReader.readLine();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

我真的希望能得到一些帮助。

4 个答案:

答案 0 :(得分:1)

100%肯定&经过测试.. 使用此代码文件将从设备读取:

public void readFile(String File) throws IOException {
        File cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "/stackover");
        //for make the directory if not exist
        if (!cacheDir.exists())
            cacheDir.mkdirs();
        File f = new File(cacheDir, File);
        FileInputStream fin = new FileInputStream(f);
        InputStreamReader isr = new InputStreamReader(fin);
        char[] ib = new char[1000];
        String str ="";
        int cr ;
        while( (cr=isr.read(ib))>0)
        {
            String s = String.copyValueOf(ib,0,cr);
            str+=s;
            ib = new char[1000];
        }
        isr.close();

    Toast.makeText(getApplicationContext(),str+"", Toast.LENGTH_SHORT).show();
    }
}

答案 1 :(得分:0)

从堆栈中看,很明显你是从Filehanlding调用SettingsActivity活动方法。

你不能这样做。为了使用与Context相关的方法,Filehandling需要是一个创建的Activity。

为了从SettingsActivity的OnClickListener中执行您想要的操作,您必须使Filehandling成为一个接收工作Activity的Context的util类。

public final class Filehandling {

    private Filehandling() {
    }

    public static void writeFile(Context context, String Filename, String Text) throws IOException {
        FileOutputStream fos = context.openFileOutput(Filename, Context.MODE_PRIVATE);
        fos.write(Text.getBytes());
        fos.close();
    }

    public sttaic void readFile(Context context, String File) throws IOException {
        try {
            BufferedReader inputReader = new BufferedReader(new InputStreamReader(context.openFileInput(File)));
            String inputString;
            StringBuffer stringBuffer = new StringBuffer();
            inputString = inputReader.readLine();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

public class IPandPort {


    public static void setIp(Context context) {
        try {
            FileHandling.writeFile(context, "file.txt", "yourtext");
        } catch (IOException e) {
            // TODO
        }
    }
}

从SettingsActivity,您可以这样做

btn.setOnClickListener(bew View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Pass a Context as SettingsActivity from anonymous listener. Note if it's not an inner class you can just pass "this"
        IPandPort.setIp(SettingsActivity.this);
    }
});

答案 2 :(得分:0)

100%确定

使用此代码文件将使用satyam文件夹写入您的Internel存储中。 试着快乐编码...

     public void writeFile(String Filename, String Text) throws IOException {

                File cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "/satyam");
                //for make the directory if not exist
                if (!cacheDir.exists())
                    cacheDir.mkdirs();

               File f = new File(cacheDir, Filename);
                FileOutputStream fout = new FileOutputStream(f);
                OutputStreamWriter osw = new OutputStreamWriter(fout);

                osw.write(Text);
                osw.flush();
                osw.close();
Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_SHORT).show();
         }

答案 3 :(得分:-1)

首先尝试检查您想要阅读的file是否存在

 File data = new File(filePath);
        if(data.exists()) {
  // your  code to read file     
  }

更新

正确地将数据写入文件:

public void writeFile(String Filename, String Text) throws IOException {
  String path = Environment.getExternalStorageDirectory() + File.separator + "/"+Filename + File.separator;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File data = new File(path);
        if (!data.createNewFile()) {
            data.delete();
            data.createNewFile();
        } 
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
        objectOutputStream.writeObject(Text.getBytes());
        objectOutputStream.close();
}