2011-12-10 9 views
1

データベースに保存したパスがtext1.txtのファイルにあります。このファイルには表示したいテキストが含まれています。ファイルはassetsフォルダ、assets/text1.txtにあります。データベースに保存されたパスを使用してassetsフォルダ内のファイルを開く方法は?

このファイルを開いてコンテンツを表示するにはどうすればよいですか?

if (placetext != null) { 
    try 
    { 
     InputStream textpath = getAssets().open(text); 
     //Bitmap bit = BitmapFactory.decodeStream(textpath); 
     placetext.setText(text); 
     //placetext.setText(text); 
    } 
    catch (IOException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

...とエミュレータ上のビューでは、ファイルの内容だけではありませんtext1.txt:

コードがあります。

iが既に溶液

ストリングtext12 = b.getString( "テキスト")を有する 試み{ 入力ストリームは= getAssets(IS)(text12)オープン。 // int size = is.available();私はここで推測

InputStream textpath = getAssets().open(text); 

:テキストを開くには、ファイルの名前を表すため、通常のだ

  byte[] buffer = new byte[size]; 
      is.read(buffer); 
      is.close(); 

      String text= new String(buffer); 

      placetext = (TextView)findViewById(R.id.detailText2); 
      placetext.setText(text); 
      } catch (IOException e) { 
       throw new RuntimeException(e); 
      } 

答えて

0

placetext.setText(text); 

これは、テキストフィールドにパラメータが渡されたので、現在はファイル名になります。

ファイルの内容をテキストフィールドに入れるには、ファイルを開いて読み込み、StringBufferに内容を格納し、StringBufferコンテンツをテキストフィールドに格納した後にファイルを開く必要があります。

EDIT:Javaでファイルの内容を読むために、他の多くの間で

StringBuilder text = new StringBuilder(); 
Scanner scanner = new Scanner(new FileInputStream(new File('yourfile'))); 
    try { 
     while (scanner.hasNextLine()){ 
     text.append(scanner.nextLine()); 
     } 
    } 
    finally{ 
     scanner.close(); 
    } 

} 

一つの解決策。

は、これは私が中/資産フォルダ保存されたXMLの内容を読み取るために使用するものであることが

+0

お礼ご回答のため。 InputStream textpath = getAssets()。open(テキスト)、textはパスを含むsqliteのフィールドを表します。それは画像ファイルと画像パスを使った作業ですが、text.txtで作業しません。 –

+0

あなたは大歓迎です! :)それは動作しますか? –

+0

いいえ、それは動作しません:( –

0

を役に立てば幸い:

public static String getXMLFromAssets(Context ctx, String pathToXML){ 
     InputStream rawInput; 
     //create a output stream to write the buffer into 
     ByteArrayOutputStream rawOutput = null; 
     try { 
      rawInput = ctx.getAssets().open(pathToXML); 
      //create a buffer that has the same size as the InputStream 
      byte[] buffer = new byte[rawInput.available()]; 
      //read the text file as a stream, into the buffer 
      rawInput.read(buffer); 
      rawOutput = new ByteArrayOutputStream(); 
      //write this buffer to the output stream 
      rawOutput.write(buffer); 
      //Close the Input and Output streams 
      rawOutput.close(); 
      rawInput.close(); 
     } catch (IOException e) { 
      Log.e("Error", e.toString()); 
     } 
     //return the output stream as a String 
     return rawOutput.toString(); 
} 
関連する問題