Preface: great majority encounter adversity struggle some time, can not be decadent. Only those who have faith, pursuit and dream can have a new life and a new beginning, and only those who have personality charm can let us respect them.
Recently, in the project development, we need to read the format in the. MTP file, but it is garbled when opened with normal text file, of course, there are special software to read it is not garbled, but a hexadecimal data.
For example, if you open it with text software, it looks like this:
We actually want something like this:
Click a button to access the phone’s memory, select the.mTP document, return and parse the data.
The result looks like this:
In I use MTP document that is generated by other software, is used to download all single chip microcomputer, and such documents can be through the android parsing out, through the code inside need android and USB_HID equipment in under the influence of communication, because each is different, the inside of the document format to get to the corresponding data can be communicate with hardware engineers over there, I’m going to record how I read the data from the.mTP document and print it out.
directory
Create MyFile class
Create the FileChooseUtil utility class
Three, implementation,
3.1 Skipping to a Folder
3.2 Setting Permissions
3.3 All Codes
Four,
Create MyFile class
This class reads files with the following code:
package com.example.readbin.MyFlie; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class MyFile { public static boolean createMyFile(File file, String name){ if (! file.exists()) { file.mkdirs(); } new_file = new File(File + "/" + name); if (! new_file.exists()) { new_file.getParentFile().mkdirs(); try { new_file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } } return true; } public static String readMyFile(File file){ String content = ""; try { FileInputStream inputStream = new FileInputStream(file); byte[] bytes = new byte[1024]; ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); while (inputStream.read(bytes) ! = -1) { arrayOutputStream.write(bytes, 0, bytes.length); } inputStream.close(); arrayOutputStream.close(); content = new String(arrayOutputStream.toByteArray()); } catch (Exception e) { } return content; } public static byte[] readFile(String filename) throws IOException {// Open the File File = new File(filename); If (file.isdirectory ()) {log.d ("TAG","The file is directory."); return null; } else if(! file.exists()) { Log.d("TAG","The File isn't exist."); return null; } else { try { FileInputStream fis = new FileInputStream(filename); byte[] b = new byte[fis.available()]; fis.read(b); fis.close(); return b; } catch (FileNotFoundException e) { throw(e); } catch (IOException e) { throw(e); } } } public static boolean WriteMyFile(File file,String content){ try { FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(content); osw.flush(); osw.close(); fos.close(); return true; } catch (IOException e) { e.printStackTrace(); return false; }}}Copy the code
Create the FileChooseUtil utility class
This utility class can get the path of the selection file, which can be found and read out later. The code is as follows:
package com.example.readbin.MyFlie; import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.widget.Toast; public class FileChooseUtil { private Context context; private static FileChooseUtil util = null; private FileChooseUtil(Context context) { this.context = context; } public static FileChooseUtil getInstance(Context context) { if (util == null) { util = new FileChooseUtil(context); } return util; } public String getChooseFileResultPath(uri uri) {String chooseFilePath = null; If ("file".equalsignorecase (uri.getScheme())) {// Open chooseFilePath = uri.getPath(); Toast.makeText(context, chooseFilePath, Toast.LENGTH_SHORT).show(); return chooseFilePath; } if (build.version.sdk_int > build.version_codes.kitkat) {//4.4 later chooseFilePath = getPath(context, uri); } else {//4.4 below system call method chooseFilePath = getRealPathFromURI(uri); } return chooseFilePath; } @param contentUri @return */ private String getRealPathFromURI(Uri contentUri) {String res = null; String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null); if (null ! = cursor && cursor.moveToFirst()) { int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); res = cursor.getString(column_index); cursor.close(); } return res; } /** * the absolute path to the file from the Uri, designed for Android4.4, */ @suppressLint ("NewApi") private String getPath(Final Context Context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?" ; final String[] selectionArgs = new String[]{split[1]}; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { uri.getPath(); } return null; } private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = {column}; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor ! = null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor ! = null) cursor.close(); } return null; } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ private boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ private boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ private boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); }}Copy the code
Three, implementation,
3.1 Skipping to a Folder
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); Try {startActivityForResult(intent.createchooser (Intent, "please select a file to upload "),READ_REQUEST_CODE); } the catch (android content. ActivityNotFoundException ex) {Toast. MakeText (MainActivity. This, please install the file manager, Toast.LENGTH_SHORT).show(); }Copy the code
3.2 Setting Permissions
Add the following permissions under androidmanifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Copy the code
Add the following additional permissions to android 10:
android:requestLegacyExternalStorage="true"
Copy the code
3.3 All Codes
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private TextView mTvReadBin; private Button mBtnSelectFile; final int READ_REQUEST_CODE = 1; String path = "file:///android_asset/USB.bin"; @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTvReadBin = findViewById(R.id.tv_bin); mBtnSelectFile = findViewById(R.id.btn_select_file); mBtnSelectFile.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_select_file: findProgammer(); break; } } private void findProgammer(){ Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); Try {startActivityForResult(intent.createchooser (Intent, "please select a file to upload "),READ_REQUEST_CODE); } the catch (android content. ActivityNotFoundException ex) {Toast. MakeText (MainActivity. This, please install the file manager, Toast.LENGTH_SHORT).show(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent resultData) { super.onActivityResult(requestCode, resultCode,resultData); if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) { // The document selected by the user won't be returned in the intent. // Instead, a URI to that document will be contained in the return intent // provided to this method as a parameter. // Pull that URI using resultData.getData(). if (resultData ! = null) { Uri uri = resultData.getData(); String filepath = FileChooseUtil.getInstance(this).getChooseFileResultPath(uri); Log.d("TAG"," path :" + filepath); // filepath = FileChooseUtil.getInstance(this).getChooseFileResultPath(uri); // Log.d("TAG",filepath); try{ byte[] binData = MyFile.readFile(filepath); mTvReadBin.setText("" + Arrays.toString(binData)); Log.d("TAG"," allow access "); } catch (IOException e){ Log.d("TAG",e.getMessage()); } } } } }Copy the code
The layout code is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" Android :id="@+id/btn_select_file" Android :text=" select file" /> <ScrollView Android :layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:id="@+id/sc_data" android:layout_below="@+id/btn_select_file" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_bin" android:text="Hello World!" /> </ScrollView> </LinearLayout>Copy the code
Four,
This is how I read the data in the.mTP file. Note that the data in the file is a hexadecimal byte and does not have negative numbers, but is converted to decimal for display. Java uses complement to represent binary numbers, so there will be negative numbers in conversion. If the above content is useful to your friends, click a praise bai ~, if there is a wrong place welcome to point out, modestly modify.