我试图将XML文件反序列化为Object。 我的代码失败了:
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());
}
}
答案 0 :(得分:2)
Android模拟器无法访问主机的文件系统。您可以将XML文件捆绑到project_root\res\raw\
文件夹中,然后将其作为资源打开:
// Open project_root\res\raw\my_file.xml
InputStream stream = getResources().openRawResource(R.raw.my_file);
或将其复制到虚拟设备的存储空间,然后打开本地路径:
adb push C:\Temp\my_file.xml /sdcard/my_file.xml