Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尝试在Android中编写文件时始终获取NullPointerException_Java_Android - Fatal编程技术网

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

Java 尝试在Android中编写文件时始终获取NullPointerException,java,android,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

我试图将设置保存到文件中,但每次写入文件时,都会出现
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();
        }
    }
}

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

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

 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();
}

从堆栈分形中可以明显看出,您正在从
SettingsActivity
调用
Filehanlding
活动方法

你不能这样做。为了使用与上下文相关的方法,文件处理需要是一个创建的活动

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的OnClickListener中实现您想要的功能,您必须使Filehandling成为一个接收工作活动上下文的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
        }
    }
}
通过设置活动,您可以这样做

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);
    }
});

100%确定

使用此代码文件将与satyam文件夹一起写入Internet存储。 试着有一个快乐的编码

     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();
         }

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();
    }
}

您是否添加了写入外部存储权限?“ankit aggarwai”这不是外部存储,而是内部存储您的文件名可能为空?不要对扩展活动的类使用
new
,可能的副本不存在。如果我没有完全理解,它应该被创建wrong@buddyspencer文件应该是在写文件的时候创建的,而不是在阅读你的案例时创建的,来说说为什么要投反对票我不认为我建议你有什么错。我很确定我没有投任何票。。。你是对的。我现在首先创建了文件,不再在异常中运行。Thx@KapilRajput我投了反对票,因为真正的问题是写文件的时候。此外,如果文件不存在,contex.openFileInput()会抛出FileNotFoundException,所以在这种情况下根本不需要检查文件是否存在。