【发布时间】:2018-11-01 19:45:55
【问题描述】:
我正在尝试将 XML 文件反序列化为对象。 我的代码上线失败:
new FileInputStream(mySearch)
java.io.FileNotFoundException。
所以,我添加了: if (exists) 块以查看是否可以通过其他方式找到该文件。
我已经用谷歌搜索了错误并阅读了其他讨论主题。基于这些讨论,我尝试了 五种 不同的方式来指定文件路径和名称。 (查看注释掉的尝试)
期望的行为是我找出路径和文件名的语法有什么问题,以便找到并反序列化文件。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.File;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 5/20/2018 T. Pfaff - Added XMLDecoder Deserialization of XML file into EquationLib/LibSets/EquationSet
//===========================================================================================
//Below are the FIVE different ways that I've tried to get it to find the file
String myFileStr = "C:\\Users\\Terence\\Documents\\Meditate-Lemniscate\\Test_Single.xml";
//String myFileStr = "c:\\users\\terence\\documents\\meditate-lemniscate\\test_single.xml";
//String myFileStr = "C:/Users/Terence/Documents/Meditate-Lemniscate/Test_Single.xml";
//String myFileStr = "c:/users/terence/documents/meditate-lemniscate/test_single.xml";
//String myFileStr = "Test_Single.xml";
//===========================================================================================
String myEqSetName = "";
Integer myCnt = 0;
EquationLib equationLib = new EquationLib();
TextView myTV = (TextView) findViewById(R.id.myTextView);
//=============================================================================
//This block of code ALWAYS results in "Does NOT Exist"
//no matter which value I use for myFileStr
File mySearch = new File(myFileStr);
boolean exists = mySearch.exists();
if (exists) {
myTV.setText("YES EXISTS: " + myFileStr);
} else {
myTV.setText("Does NOT Exist: " + myFileStr);
}
//==============================================================================
XMLDecoder decoder=null;
// The first statement in the try block throws the exception:
//java.io.FileNotFoundException: C:\Users\Terence\Documents\Meditate-Lemniscate\Test_Single.xml (No such file or directory)
try{
FileInputStream myFileIS = new FileInputStream(mySearch);
decoder = new XMLDecoder(new BufferedInputStream(myFileIS));
equationLib = (EquationLib) decoder.readObject();
myCnt = equationLib.libSets.size();
myEqSetName = equationLib.libSets.get(0).equationSet.name;
} catch (Exception e){
e.printStackTrace();
}
//myTV.setText(myCnt.toString());
}
}
【问题讨论】:
-
打开
cmd窗口,切换到那个目录,输入dir;然后将输出复制/粘贴到您的问题中(使用代码格式) -
您没有尝试不同的方式来指定文件名,而是真的验证了文件是否存在?例如。在命令行上运行
dir C:\Users\Terence\Documents\Meditate-Lemniscate\Test_Single.xml。 -
那些路径看起来像 Windows 路径,但你的代码使用的是 Android 库,它在哪里运行?
-
@Andreas - dir 命令显示文件存在并显示其大小。