Java 返回空指针异常的Openfileinput
我使用以下代码创建并写入文件Java 返回空指针异常的Openfileinput,java,android,file-io,fileinputstream,Java,Android,File Io,Fileinputstream,我使用以下代码创建并写入文件 FileOutputStream fOut = mcontext.openFileOutput("msg.txt",Context.MODE_WORLD_READABLE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write("abc"); osw.flush(); osw.close(); 但是在日志cat中,它在上述代码的第一行给出了null指针异
FileOutputStream fOut = mcontext.openFileOutput("msg.txt",Context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("abc");
osw.flush();
osw.close();
但是在日志cat中,它在上述代码的第一行给出了null指针异常
这是全部代码
public class Server implements Runnable
{
private String address ="127.0.0.1";
private String add="127.0.0.2";
private static Context mcontext;
byte[] buf = new byte[256];
DatagramSocket socket;
@Override
public void run()
{
try{
InetAddress serveradd = InetAddress.getByName(address);
InetAddress clientadd = InetAddress.getByName(add);
socket=new DatagramSocket(6000,serveradd);
Log.d("UDP", "S: Connecting...");
DatagramPacket packet=new DatagramPacket(buf,buf.length);
socket.receive(packet);
Log.d("UDP", "S: Receiving...");
/* Receive the UDP-Packet */
String data=new String(packet.getData());
String phno=data.substring(0,9);
String identity=data.substring(10,14);
//FileWriter f = new FileWriter("/sdcard/download/msg.txt");
// I/O operation
FileOutputStream fOut = mcontext.openFileOutput("msg.txt",Context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("gfdffg");
osw.flush();
osw.close();
Log.d("UDP", "S: ReceivedJI: '" + new String(packet.getData()) + "'");
Log.d("UDP", "S: Done.");
//Toast.makeText(context.getApplicationContext(),"received"+new String(packet.getData()),Toast.LENGTH_LONG).show();
// if(TextUtils.isDigitsOnly(phno) && identity.equals("novel"))
// {
byte[] bufsend =("hi").getBytes();
Log.d("UDP", "S: sending.");
DatagramPacket packetsend=new DatagramPacket(bufsend,bufsend.length,clientadd,5000);
socket.send(packetsend);
Log.d("UDP", "S: send.'"+bufsend+"'");
//}
//else
// {
//Log.d("UDP", "S: not matched.");
// }
}
catch (Exception e)
{
Log.e("UDP", "S: Error", e);
e.printStackTrace();
//Toast.makeText(context.getApplicationContext(),"received"+e,Toast.LENGTH_LONG).show();
}
}
}
将此添加到manifest.xml将不胜感激
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
使用
mcontext
时,您没有在代码中的任何位置设置它。因此变量为null
。你应该给你的可运行的一个构造函数,它接受一个上下文
:
public Server(Context context) {
mcontext = context;
}
因此可以设置mcontext变量。另外,不要将其设为静态。变量集mcontext
在哪里?你能出示密码吗?谢谢回复,让我试试