간단한 텍스트 파일 읽기
샘플 Android 애플리케이션에서 간단한 텍스트 파일을 읽으려고합니다. 간단한 텍스트 파일을 읽기 위해 아래 작성된 코드를 사용하고 있습니다.
InputStream inputStream = openFileInput("test.txt");
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
내 질문은 :이 "test.txt"
파일을 프로젝트의 어디에 배치해야 합니까?. 나는 아래의 파일을 넣어 시도 "res/raw"
및 "asset"
폴더하지만 난 얻을 exception "FileNotFound"
위의 작성된 코드의 첫 번째 라이브가 실행됩니다 때.
도와 주셔서 감사합니다
텍스트 파일을 /assets
Android 프로젝트 아래의 디렉토리에 배치하십시오. AssetManager
클래스를 사용 하여 액세스하십시오.
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
또는 파일을 /res/raw
디렉토리 에 넣을 수도 있습니다 . 여기서 파일은 색인화되며 R 파일의 id로 액세스 할 수 있습니다.
InputStream is = context.getResources().openRawResource(R.raw.test);
이 시도,
package example.txtRead;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class txtRead extends Activity {
String labels="caption";
String text="";
String[] s;
private Vector<String> wordss;
int j=0;
private StringTokenizer tokenizer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wordss = new Vector<String>();
TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(readTxt());
}
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.toc);
// InputStream inputStream = getResources().openRawResource(R.raw.internals);
System.out.println(inputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
}
이것이 내가하는 방법입니다.
public static String readFromAssets(Context context, String filename) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));
// do reading, usually loop until end of file reading
StringBuilder sb = new StringBuilder();
String mLine = reader.readLine();
while (mLine != null) {
sb.append(mLine); // process line
mLine = reader.readLine();
}
reader.close();
return sb.toString();
}
다음과 같이 사용하십시오.
readFromAssets(context,"test.txt")
Having a file in your assets
folder requires you to use this piece of code in order to get files from the assets
folder:
yourContext.getAssets().open("test.txt");
In this example, getAssets()
returns an AssetManager
instance and then you're free to use whatever method you want from the AssetManager
API.
In Mono For Android....
try
{
System.IO.Stream StrIn = this.Assets.Open("MyMessage.txt");
string Content = string.Empty;
using (System.IO.StreamReader StrRead = new System.IO.StreamReader(StrIn))
{
try
{
Content = StrRead.ReadToEnd();
StrRead.Close();
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
}
StrIn.Close();
StrIn = null;
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
To read the file saved in assets folder
public static String readFromFile(Context context, String file) {
try {
InputStream is = context.getAssets().open(file);
int size = is.available();
byte buffer[] = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (Exception e) {
e.printStackTrace();
return "" ;
}
}
Here is a simple class that handles both raw
and asset
files :
public class ReadFromFile {
public static String raw(Context context, @RawRes int id) {
InputStream is = context.getResources().openRawResource(id);
int size = 0;
try {
size = is.available();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return readFile(size, is);
}
public static String asset(Context context, String fileName) {
InputStream is = null;
int size = 0;
try {
is = context.getAssets().open(fileName);
AssetFileDescriptor fd = null;
fd = context.getAssets().openFd(fileName);
size = (int) fd.getLength();
fd.close();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return readFile(size, is);
}
private static String readFile(int size, InputStream is) {
try {
byte buffer[] = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
For example :
ReadFromFile.raw(context, R.raw.textfile);
And for asset files :
ReadFromFile.asset(context, "file.txt");
참고URL : https://stackoverflow.com/questions/5771366/reading-a-simple-text-file
'Programing' 카테고리의 다른 글
start-stop-daemon으로 시작한 프로세스의 stdout을 어떻게 기록 할 수 있습니까? (0) | 2020.07.21 |
---|---|
반응, ES6-getInitialState가 일반 JavaScript 클래스에 정의되었습니다. (0) | 2020.07.21 |
IPython Notebook Server 3에서 함수 인수를 어떻게 볼 수 있습니까? (0) | 2020.07.21 |
부울 크기가 1 비트가 아닌 1 바이트 인 이유는 무엇입니까? (0) | 2020.07.21 |
ViewController가 모달로 표시되는지 확인할 수 있습니까? (0) | 2020.07.21 |