Saturday, July 25, 2015

Android read file "/proc/mounts"

Android example code to read "/proc/mounts", easy to be modified to read other text files.


com.example.android_proc_mounts.MainActivity.java
package com.example.android_proc_mounts;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MainActivity extends ActionBarActivity {

    TextView info;
    String targetPath = "/proc/mounts";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        info = (TextView)findViewById(R.id.info);
        info.setText(ReadFile(targetPath));
    }

    private String ReadFile(String path){
        String result = "";

        File file = new File(path);
        if(file.exists()){
            result += path + ":\n"
                    + "======\n";
            Scanner scanner = null;
            try {
                scanner = new Scanner(file);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    result += line + "\n"
                            + "------\n";
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                result += e.toString();
            }

        }else{
            return (path + " NOT exists");
        }

        return result;
    }
}


layout/activity_main.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>


No comments:

Post a Comment