반응형
Android 텍스트 파일은 어떻게 읽나요?
텍스트 파일에서 텍스트를 읽고 싶습니다.다음 코드에서는 예외가 발생합니다(즉, 다음 코드에서는catch블록)을 클릭합니다.텍스트 파일을 응용 프로그램 폴더에 넣었습니다.이 텍스트 파일(mani.txt)을 올바르게 읽으려면 어디에 두어야 합니까?
try
{
InputStream instream = openFileInput("E:\\test\\src\\com\\test\\mani.txt");
if (instream != null)
{
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line,line1 = "";
try
{
while ((line = buffreader.readLine()) != null)
line1+=line;
}catch (Exception e)
{
e.printStackTrace();
}
}
}
catch (Exception e)
{
String error="";
error=e.getMessage();
}
다음을 시도해 보십시오.
당신의 텍스트 파일은 sd카드에 있을 겁니다.
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
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) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text.toString());
다음 링크도 도움이 됩니다.
Android의 SD카드에서 텍스트 파일을 읽는 방법은 무엇입니까?
sd카드에서 파일을 읽고 싶다면.그렇다면 다음 코드가 도움이 될 수 있습니다.
StringBuilder text = new StringBuilder();
try {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"testFile.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
Log.i("Test", "text : "+text+" : end");
text.append('\n');
} }
catch (IOException e) {
e.printStackTrace();
}
finally{
br.close();
}
TextView tv = (TextView)findViewById(R.id.amount);
tv.setText(text.toString()); ////Set the text to text view.
}
}
자산 폴더에서 파일을 읽으려면
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
또는 이 파일을 읽으려면res/rawfoldery: 파일이 색인화되어 R 파일의 ID로 액세스할 수 있습니다.
InputStream is = getResources().openRawResource(R.raw.test);
자산 폴더에 텍스트 파일 저장...해당 폴더에서 파일 읽기(Read)...
아래 참조 링크 참조...
http://www.technotalkative.com/android-read-file-from-assets/
http://sree.cc/google/reading-text-file-from-assets-folder-in-android
도움이 되길...
이 코드를 사용해 보세요.
public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
String aBuffer = "";
try {
File myFile = new File(pathRoot + nameFile);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow;
}
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return aBuffer;
}
먼저 텍스트 파일을 raw 폴더에 저장합니다.
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2)
continue;
long id = addWord(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}
이거 드셔보세요
try {
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line="";
String s ="";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
while (line != null)
{
s = s + line;
s =s+"\n";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
tv.setText(""+s);
}
작은 텍스트 파일의 가장 짧은 형식(Kotlin):
val reader = FileReader(path)
val txt = reader.readText()
reader.close()
언급URL : https://stackoverflow.com/questions/12421814/how-can-i-read-a-text-file-in-android
반응형
'IT' 카테고리의 다른 글
| Spring MVC 컨트롤러 메서드에서 값이 반환되지 않을 경우 반환되는 항목 (0) | 2022.11.27 |
|---|---|
| MySQL에서의 교차 대신 (0) | 2022.11.27 |
| MariaDB - JSON 어레이를 인덱싱할 수 있습니까? (0) | 2022.11.27 |
| MySQL: 신호에 적합한 SQLSTATE 값을 선택하려면 어떻게 해야 합니다. (0) | 2022.11.27 |
| 'str' 개체에 특성 'filename'이 없습니다.Python 3 오류? (0) | 2022.11.27 |