Java 写入随机访问文件时出现NullPointerException
我可以在创建随机访问文件后直接写入该文件,但一旦尝试从函数写入,它就会中断Java 写入随机访问文件时出现NullPointerException,java,swing,nullpointerexception,randomaccessfile,Java,Swing,Nullpointerexception,Randomaccessfile,我可以在创建随机访问文件后直接写入该文件,但一旦尝试从函数写入,它就会中断 private void openFile() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY ); int result = fileChooser.showSaveDialog( this ); // user clic
private void openFile()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY );
int result = fileChooser.showSaveDialog( this );
// user clicked Cancel button on dialog
if ( result == JFileChooser.CANCEL_OPTION )
{
return;
}
File fileName = fileChooser.getSelectedFile();
if ( fileName == null || fileName.getName().equals( "" ) )
{
JOptionPane.showMessageDialog( this,
"Invalid File Name",
"Invalid File Name",
JOptionPane.ERROR_MESSAGE );
}
else
{
// Open the file
try
{
RandomAccessFile output = new RandomAccessFile( fileName, "rw" );
createRecord();
}
catch ( IOException e )
{
JOptionPane.showMessageDialog( this,
"File does not exist",
"Invalid File Name",
JOptionPane.ERROR_MESSAGE );
}
}
}
private void createRecord()
{
String firstName = tfdFirst.getText();
String lastName = tfdLast.getText();
String emailAddress = tfdEmail.getText();
String homeAddress = tfdAddress.getText();
Long phoneNumber = new Long(tfdPhone.getText());
char gender = tfdGender.getText().charAt(0);
System.out.println(firstName + lastName + emailAddress + homeAddress + phoneNumber + gender);
try
{
output.seek(0);
output.writeChar(gender);
writeString( output, lastName);
writeString( output, firstName);
writeString( output, emailAddress);
writeString( output, homeAddress);
output.writeLong(phoneNumber);
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
很抱歉代码墙,但这是两个有问题的函数。第一个尝试打开一个名为output的RandomAccessFile,然后调用createRecord()
,尝试将用户输入从JFrame写入该文件。如果我把一个简单的writeInt()
函数放在createRecord()
的位置,那么它可以正常工作,但是一旦调用了createRecord()
,就好像输出不存在一样
我已经为此工作了几个小时,但毫无结果,所以如果有人能帮我找到解决办法,我将不胜感激
编辑:根据请求堆叠跟踪。(警告,很长…)
你似乎有一个阴影问题 您已经在
openFile
中创建了一个局部变量output
RandomAccessFile output = new RandomAccessFile( fileName, "rw" );
output.seek(0);
但是是access,它似乎是createRecord
中的一个实例变量
RandomAccessFile output = new RandomAccessFile( fileName, "rw" );
output.seek(0);
实例变量很可能是null
RandomAccessFile output = new RandomAccessFile( fileName, "rw" );
output.seek(0);
通常,我会建议删除重新声明并使用实例字段,但在本文中,我认为您应该去掉实例字段,并将RandomAccessFile
的引用传递给createRecord
方法
你也没有管理你的资源,记住如果你打开了,你必须关闭它
try (RandomAccessFile output = new RandomAccessFile( fileName, "rw" ))
{
createRecord(output);
}
catch ( IOException e )
{
JOptionPane.showMessageDialog( this,
"File does not exist",
"Invalid File Name",
JOptionPane.ERROR_MESSAGE );
}
查看更多详细信息堆栈跟踪,请同时指出导致NPEI的行,甚至不知道此代码是如何编译的<代码>输出在
createRecord()
@fge中未声明,存在问题,输出
可能是一个实例字段。哦,对不起,输出是在保存这些函数的类中声明的。导致NPE的行是我试图写入createRecord中的文件的地方。谢谢!现在可以了。另外,我计划稍后添加关闭代码,我想确保我可以先编写。不关闭文件可能会导致文件无法刷新,只要您知道;)