How does Android get file-related information through the file path, such as file name, file size, creation time, relative path of the file, absolute path of the file, etc.:
As shown in the figure:
Code:
public class MainActivity extends Activity { private String path = "/storage/emulated/0/Android/data/cn.wps.moffice_eng/mm.doc"; private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView(R.layout.activity_main); initView(); } @SuppressLint("SimpleDateFormat") private void initView() { // TODO Auto-generated method stub mTextView = (TextView) findViewById(R.id.textview); File f = new File(path); if (f.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(f); String time = new SimpleDateFormat("yyyy-MM-dd") .format(new Date(f.lastModified())); System.out.println("File creation time" + time); System.out.println("File size:" + ShowLongFileSzie(f.length()));// Calculate file size // B,KB,MB, System.out.println("文件大小:" + fis.available() + "B"); System.out.println("File name: " + f.getName()); System.out.println("Does the file exist: " + f.exists()); System.out.println("The relative path of the file: " + f.getPath()); System.out.println("Absolute path of file: " + f.getAbsolutePath()); System.out.println("File can be read: " + f.canRead()); System.out.println("File can be written: " + f.canWrite()); System.out.println("File parent path: " + f.getParent()); System.out.println("File size: " + f.length() + "B"); System.out.println("File last modified time: " + new Date(f.lastModified())); System.out.println("Is it a file type: " + f.isFile()); System.out.println("Is it a folder type: " + f.isDirectory()); mTextView.setText("File creation time:" + time + "\n" + "File size:" + ShowLongFileSzie(f.length()) + "\n" + "File name:" + f.getName() + "\n" + "Does the file exist:" + f.exists() + "\n" + "The relative path of the file:" + f.getPath() + "\n" + "The absolute path of the file:" + f.getAbsolutePath() + "\n" + "File can be written:" + f.canWrite() + "\n" + "Is it a folder type:" + f.isDirectory()); } catch (Exception e) { e.printStackTrace (); } } } /**** * Calculate file size * * @param length * @return */ public String ShowLongFileSzie(Long length) { if (length >= 1048576) { return (length / 1048576) + "MB"; } else if (length >= 1024) { return (length / 1024) + "KB"; } else if (length < 1024) { return length + "B"; } else { return "0KB"; } } }
Don't forget to add permissions in AndroidManifest.xml!
<!-- SD card permissions--> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
Source code click to download