I want to run the code below to access and read the .txt file from external storage and set the textView area. You can see a detailed description of the problem below.
MainActivity
package kr.ex.colortextviewer;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private static final int READ_REQUEST_CODE = 42;
private static final int PERMISSION_REQUEST_STORAGE = 1000;
Dialog dialog;
Spinner bgc;
Spinner tc;
TextView textRead;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textRead = (TextView) findViewById(R.id.textRead);
// 권한 요청
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_STORAGE);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_option, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.close:
finish();
break;
case R.id.colorChange:
dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 타이틀 제거
dialog.setContentView(R.layout.dialog);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Window window = dialog.getWindow();
window.setAttributes(lp);
LinearLayout main_layout = (LinearLayout) findViewById(R.id.main_layout);
bgc = (Spinner) dialog.findViewById(R.id.backgroundColor);
tc = (Spinner) dialog.findViewById(R.id.textColor);
Button button_yes = (Button) dialog.findViewById(R.id.button_yes);
dialog.show();
bgc.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
button_yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
main_layout.setBackgroundResource(R.color.white);
}
});
break;
case 1:
button_yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
main_layout.setBackgroundResource(R.color.black);
}
});
break;
case 2:
button_yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
main_layout.setBackgroundResource(R.color.red);
}
});
break;
case 3:
button_yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
main_layout.setBackgroundResource(R.color.orange);
}
});
break;
case 4:
button_yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
main_layout.setBackgroundResource(R.color.blue);
}
});
break;
case 5:
button_yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
main_layout.setBackgroundResource(R.color.yellow);
}
});
break;
case 6:
button_yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
main_layout.setBackgroundResource(R.color.green);
}
});
break;
case 7:
button_yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
main_layout.setBackgroundResource(R.color.pink);
}
});
break;
case 8:
button_yes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
main_layout.setBackgroundResource(R.color.purple);
}
});
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
tc.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
case R.id.textFile:
System.out.println("파일 불러오기");
perfromFileSearch();
}
return true;
}
// 파일 내용 읽기
private String readText(String input) {
File file = new File(Environment.getExternalStorageDirectory(), input);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append("\n");
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return text.toString();
}
// 파일 양식 저장소 선택
private void perfromFileSearch() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
String path = uri.getPath();
path= path.substring(path.indexOf(":") + 1);
if (path.contains("emulated")) {
path = path.substring(path.indexOf("0") + 1);
}
Toast.makeText(this, "" + path, Toast.LENGTH_SHORT).show();
textRead.setText(readText(path));
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_STORAGE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "권한 승인", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "권한 승인이 안됨", Toast.LENGTH_SHORT).show();
finish();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
You can view the file, but when you click the text file, the log displays an error and the text does not appear in the text file in TextView.
I have already included permissions in AndroidManifest.xml;
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="kr.ex.colortextviewer">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:requestLegacyExternalStorage="true"
android:icon="@mipmap/ic_launcher"
android:label="컬러 텍스트뷰어"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ColorTextViewer"
android:fullBackupContent="@xml/backup_descriptor">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
It's an error that appears in the log.
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:492)
at java.io.FileInputStream.<init>(FileInputStream.java:160)
at java.io.FileReader.<init>(FileReader.java:72)
at kr.ex.colortextviewer.MainActivity.readText(MainActivity.java:206)
at kr.ex.colortextviewer.MainActivity.onActivityResult(MainActivity.java:241)
at android.app.Activity.dispatchActivityResult(Activity.java:8550)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5534)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5582)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8595)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Linux.open(Native Method)
at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8456)
at libcore.io.IoBridge.open(IoBridge.java:478)