Я хочу получить файл xml от пользователя и извлечь из него данные в android. как преобразовать файл в объект File.
Вот мой код при нажатии кнопки добавления файла.
public void addFile(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, 10);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @NonNull Intent data) {
if (requestCode == 10 && resultCode == RESULT_OK) {
Uri uri = data.getData();
File file = createFile(path); //next code snippet
Intent intent = new Intent(getApplicationContext(), createTableFromXml.class);
Log.d("timeTable", "created table called");
intent.putExtra("file", file.toString());
startActivity(intent);
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
Это метод создания файла
private File createFile(Uri uri) {
Log.d("timeTable", "selected path = " + uri.getPath());
StringBuilder stringBuilder = new StringBuilder();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(inputStream)));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
}
catch (IOException e) { e.printStackTrace(); }
String s = stringBuilder.toString();
output.setText(s); //this gives output of content of file
File f = new File(s); //it shows file empty
return f;
}
Это вызывает действие createTableFrom Xml, которое извлекает данные из этого xml файла.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_table_processing);
File file = new File(getIntent().getExtras().getString("file"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document= null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(file);
}
catch (ParserConfigurationException | SAXException | IOException e) {
Log.d("timeTable", String.valueOf(e)); // error getting the file
}
NodeList subjectNameList = document.getElementsByTagName("Details");
// some processing on this thats works fine in java using file path on my computer
}
Файловый объект не создается, но строка содержит данные.
Как сделать взять файл xml у пользователя и обработать его.