एसेट्स फोल्डर से फाइल पढ़ना (केवल पढ़ने योग्य)
महत्वपूर्ण: एंड्रॉइड में एसेट्स फोल्डर केवल पढ़ने योग्य (read-only) होता है। आप रनटाइम पर इसमें फाइल नहीं लिख सकते। यह उदाहरण एसेट्स से फाइल पढ़ने का सही तरीका दिखाता है।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनें।
चरण 2: लेआउट में बटन और TextView
res/layout/activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btnReadFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_above="@id/textView"
android:layout_marginBottom="15dp"
android:text="फाइल पढ़ें"/>
<TextView
android:id="@+id/textView"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold|italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
चरण 3: एसेट्स फोल्डर में फाइल बनाएं
- प्रोजेक्ट पर राइट-क्लिक → New → Folder → Assets Folder
- assets फोल्डर पर राइट-क्लिक → New → File → नाम
Quotes.txt - कोई भी टेक्स्ट कंटेंट जोड़ें
चरण 4: एसेट्स से फाइल पढ़ें
src/MainActivity.java:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button = findViewById(R.id.btnReadFile);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String string = "";
InputStream inputStream = null;
try {
inputStream = getAssets().open("Quotes.txt");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
string = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try { inputStream.close(); } catch (IOException ignored) {}
}
}
textView.setText(string);
}
});
}
}
नोट: फाइल लिखने के लिए
रनटाइम पर फाइल लिखने के लिए openFileOutput() (इंटरनल स्टोरेज) या getExternalFilesDir() (एक्सटर्नल स्टोरेज) का उपयोग करें।
ऐप चलाएं
"फाइल पढ़ें" बटन दबाकर एसेट्स फाइल का कंटेंट देखें।