Файл с сырым исходным текстом для Android
Все просто, но не работает так, как предполагалось.
У меня есть текстовый файл, добавленный как исходный ресурс. Текстовый файл содержит текст:
b) ЕСЛИ ПРИМЕНИМОЕ ЗАКОНОДАТЕЛЬСТВО ТРЕБУЕТ ЛЮБЫХ ГАРАНТИЙ В ОТНОШЕНИИ К ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ, ВСЕ ТАКИЕ ГАРАНТИИ ОГРАНИЧИВАЕТСЯ В ПРОДОЛЖИТЕЛЬНОСТЬЮ ДЕВЯТОЙ (90) ДНИ ОТ ДАТА ПОСТАВКИ.
(c) НЕТ УСТНОЙ ИЛИ ПИСЬМЕННОЙ ИНФОРМАЦИИ ИЛИ КОНСУЛЬТАЦИЯ, ПРЕДОСТАВЛЯЕМАЯ ВИРТУАЛЬНЫМ ОРИЕНТИРОВАНИЕМ, ЕГО ДИЛЕРЫ, ДИСТРИБЬЮТОРЫ, АГЕНТЫ ИЛИ СОТРУДНИКИ СОЗДАЮТ ГАРАНТИЮ ИЛИ В ЛЮБОЙ ПУТЬ УВЕЛИЧИВАЮТ ОБЪЕМ ЛЮБОГО ГАРАНТИЯ, ПРЕДОСТАВЛЯЕМАЯ ВЕРНУТЬСЯ.
(d) (только для США) НЕКОТОРЫЕ СОСТОЯНИЯ НЕ ПОЗВОЛЯЙТЕ ИСКЛЮЧЕНИЕ ПОДРАЗУМЕВАЕМЫХ ГАРАНТИИ, ТАК ВЫШЕ ИСКЛЮЧАЮТ МОГУТ НЕ ПРИМЕНЯЕТСЯ К ВАМ. ЭТОТ ГАРАНТИЯ ВЫ КОНКРЕТНЫЕ ЮРИДИЧЕСКИЕ ПРАВА И ВЫ МОЖЕТЕ ТАКЖЕ ИМЕЮТ ДРУГИЕ ЮРИДИЧЕСКИЕ ПРАВА, ЧТО ВАРИАНТЫ ОТ ГОСУДАРСТВА В ГОСУДАРСТВО.
На моем экране у меня есть такой макет:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1.0"
android:layout_below="@+id/logoLayout"
android:background="@drawable/list_background">
<ScrollView android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/txtRawResource"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="3dip"/>
</ScrollView>
</LinearLayout>
Код для чтения исходного ресурса:
TextView txtRawResource= (TextView)findViewById(R.id.txtRawResource);
txtDisclaimer.setText(Utils.readRawTextFile(ctx, R.raw.rawtextsample);
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
return null;
}
return byteArrayOutputStream.toString();
}
Текст появляется, но после каждой строки я получаю странный символ [] Как я могу удалить этот символ? Я думаю, что это новая линия.
РАБОЧЕЕ РЕШЕНИЕ
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
Ответы
Ответ 1
Что делать, если вы используете BufferedReader на основе символов вместо байт-основанного InputStream?
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) { ... }
Не забывайте, что readLine()
пропускает новые строки!
Ответ 2
Вы можете использовать это:
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.help);
byte[] b = new byte[in_s.available()];
in_s.read(b);
txtHelp.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
txtHelp.setText("Error: can't show help.");
}
Ответ 3
Если вы используете IOUtils из apache "commons-io", это еще проще:
InputStream is = getResources().openRawResource(R.raw.yourNewTextFile);
String s = IOUtils.toString(is);
IOUtils.closeQuietly(is); // don't forget to close your streams
Зависимости: http://mvnrepository.com/artifact/commons-io/commons-io
Maven:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Gradle:
'commons-io:commons-io:2.4'
Ответ 4
Скорее сделайте это так:
// reads resources regardless of their size
public byte[] getResource(int id, Context context) throws IOException {
Resources resources = context.getResources();
InputStream is = resources.openRawResource(id);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] readBuffer = new byte[4 * 1024];
try {
int read;
do {
read = is.read(readBuffer, 0, readBuffer.length);
if(read == -1) {
break;
}
bout.write(readBuffer, 0, read);
} while(true);
return bout.toByteArray();
} finally {
is.close();
}
}
// reads a string resource
public String getStringResource(int id, Charset encoding) throws IOException {
return new String(getResource(id, getContext()), encoding);
}
// reads an UTF-8 string resource
public String getStringResource(int id) throws IOException {
return new String(getResource(id, getContext()), Charset.forName("UTF-8"));
}
Из Activity добавьте
public byte[] getResource(int id) throws IOException {
return getResource(id, this);
}
или из тестового примера, добавьте
public byte[] getResource(int id) throws IOException {
return getResource(id, getContext());
}
И следите за обработкой ошибок - не ловите и игнорируете исключения, когда ваши ресурсы должны существовать или что-то (очень?) неправильно.
Ответ 5
Это еще один метод, который определенно будет работать, но я не могу его прочитать для чтения нескольких текстовых файлов для просмотра в нескольких текстовых просмотров в одном действии, кто может помочь?
TextView helloTxt = (TextView)findViewById(R.id.yourTextView);
helloTxt.setText(readTxt());
}
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourTextFile);
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();
}
Ответ 6
@borislemke вы можете сделать это аналогичным образом, например
TextView tv ;
findViewById(R.id.idOfTextView);
tv.setText(readNewTxt());
private String readNewTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile);
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();
}
Ответ 7
Здесь идет смесь выходных дней и решений Vovodroid.
Это более корректно, чем решение Vovodroid и более полное, чем недельное решение.
try {
InputStream inputStream = res.openRawResource(resId);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
} finally {
reader.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
// process exception
}
Ответ 8
1. Сначала создайте папку Directory и назовите ее raw внутри папки res
2.create.txt файл внутри папки исходного каталога, которую вы создали ранее, и дать ему любое имя eg.articles.txt....
3.copy и вставьте текст, который вы хотите, в файл .txt, который вы создали "articles.txt",
4.dont забудьте включить текстовое изображение в свой main.xml
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gettingtoknowthe_os);
TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos);
helloTxt.setText(readTxt());
ActionBar actionBar = getSupportActionBar();
actionBar.hide();//to exclude the ActionBar
}
private String readTxt() {
//getting the .txt file
InputStream inputStream = getResources().openRawResource(R.raw.articles);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
int i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
Надеюсь, что это сработало!
Ответ 9
InputStream is=getResources().openRawResource(R.raw.name);
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuffer data=new StringBuffer();
String line=reader.readLine();
while(line!=null)
{
data.append(line+"\n");
}
tvDetails.seTtext(data.toString());
Ответ 10
Вот простой способ прочитать текстовый файл из необработанной папки:
public static String readTextFile(Context context,@RawRes int id){
InputStream inputStream = context.getResources().openRawResource(id);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int size;
try {
while ((size = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, size);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
Ответ 11
Вот реализация в Котлине
try {
val inputStream: InputStream = this.getResources().openRawResource(R.raw.**)
val inputStreamReader = InputStreamReader(inputStream)
val sb = StringBuilder()
var line: String?
val br = BufferedReader(inputStreamReader)
line = br.readLine()
while (line != null) {
sb.append(line)
line = br.readLine()
}
br.close()
var content : String = sb.toString()
Log.d(TAG, content)
} catch (e:Exception){
Log.d(TAG, e.toString())
}
Ответ 12
Ну, с Kotlin вы можете сделать это только в одной строке кода:
resources.openRawResource(R.raw.rawtextsample).bufferedReader().use { it.readText() }
Или даже объявить функцию расширения:
fun Resources.getRawTextFile(@RawRes id: Int) =
openRawResource(id).bufferedReader().use { it.readText() }
А потом просто используйте это сразу:
val txtFile = resources.getRawTextFile(R.raw.rawtextsample)