2011-01-04 3 views
0

Я просто работаю через главу по управлению ресурсами приложений и меня немного неприятностей со следующим:Как выводить содержимое исходных файлов

"Add a raw text file resource to the Droid1 project. Use the openRawResourse() method to create an InputStream object and read the file. Output the contents of the file by using Log.v() method. Rerun the application and view the result."

Итак, во-первых, я сразу же нажал на папку Рез , создал новую необработанную папку и перетащил txt-файл с моего рабочего стола в это (думаю, это было нормально и не удалось найти другой способ импорта файла).

Тогда я написал эти две линии:

InputStream iFile = getResources().openRawResource(R.raw.textfile); 
Log.v(TAG, iFile); 

Однако я получаю ошибку:

"The method v(String, String) in the type Log is not applicable for the arguments (String, InputStream)"

Не уверен, что делать ... любые предложения. Благодарю.

ответ

1

Поскольку ошибка указывает, что вторым параметром для v-метода должен быть тип данных String. Таким образом, вам нужно преобразовать InputStream iFile в строку.

я ссылка http://www.kodejava.org/examples/266.html

Вам понадобятся следующие импорт в вашей деятельности:

import java.io.IOException; 
import java.io.InputStream; 
import java.io.StringWriter; 
import java.io.Writer; 
import java.io.Reader; 
import java.io.BufferedReader; 
import java.io.InputStreamReader; 

И сам метод:

public String convertStreamToString(InputStream is) throws IOException { 

    /* To convert the InputStream to String we use the 
    * Reader.read(char[] buffer) method. We iterate until the 
    * Reader return -1 which means there's no more data to 
    * read. We use the StringWriter class to produce the string.*/ 
    if (is != null) { 
     Writer writer = new StringWriter(); 
     char[] buffer = new char[1024]; 
    try { 
     Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); 
     int n; 
     while ((n = reader.read(buffer)) != -1) { 
      writer.write(buffer, 0, n); 
     } 
    } finally { 
     is.close(); 
    } 
    return writer.toString(); 
    } else {   
     return ""; 
    } 

} 

Пройди свой InputStream в метод, чтобы получить ваш String и Log.v

InputStream iFile = getResources().openRawResource(R.raw.textfile); 
String strInput = null; 
try { 
    strInput = convertStreamToString(iFile); 
} catch (IOException e) { 
    Log.v(TAG, "The string conversion failed."); 
} 
if(strInput != null){ 
    Log.v(TAG, strInput); 
} 
Смежные вопросы