Data Storage - Text aus Datei auslesen

  • Antworten:3
Alex W.
  • Forum-Beiträge: 84

20.06.2010, 20:21:59 via Website

Hallo,

hab ein Anfänger Problem und finde in der Doku einfach keine Hilfe.

Ich schreibe über ...


1String FILENAME = "hello_file";
2 String string = "hello world!";
3
4
5 try {
6 FileOutputStream fos = openFileOutput(FILENAME,
7 Context.MODE_PRIVATE);
8 fos.write(string.getBytes());
9 fos.close();
10
11......



... in eine Datei.

Wie kann ich diesen Text wieder auslesen? Ich lese in der Doku das ich ein FileInputStream erzeugen muss und mit read() auslesen (siehe Originaltext unten). Aber wie kann ich diese bytes wieder in Text umwandeln (soll auf eine Textview gelegt werden)? Die üblichen Verdächtigen hab ich schon probiert. Also sowas wie


1FileInputStream fis = openFileInput(FILENAME);
2fis.read();
3String s1 = String.valueOf( fis );

oder :

1FileInputStream fis = openFileInput(FILENAME);
2fis.read();
3String s2 = fis.toString();

oder:

CharSequence chars = fis.toString();


Danach geb ich der Textview mit TextViewA2.setText(fis) den Text der Datei (natürlich vorher deklariert: TextView TextViewA2 = (TextView) findViewById(R.id.a2);) .

Es funktioniert einfach nicht. Entweder erscheint da sowas wie "java.io.FileInputStream@4354567" als Text auf der Textview oder es hagelt Abstürze, je nachdem in welcher Kombi.

Die Doku sagt hier:

To read a file from internal storage:

Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
Read bytes from the file with read().
Then close the stream with close().

Bitte bitte um Hilfe, ich tu jetzt schon ewig rum... :-):confused:

Antworten
Mac Systems
  • Forum-Beiträge: 1.727

20.06.2010, 20:35:27 via Website

Du musst schon aktiv aus der Datei lesen, ja und ein Java Buch das einem die Basics vermittelt ist ebenso wichtig wie munter drauf rumprobieren!

1/**
2 * Reads from given <code>InputStream</code> into a
3 * <code>StringBuffer</code>.
4 *
5 * @param _instream
6 * @return
7 * @throws IOException
8 */
9 public static StringBuilder asString(final InputStream _instream) throws IOException
10 {
11 if (_instream == null)
12 {
13 throw new NullPointerException("InputStream");
14 }
15
16 final BufferedReader reader = new BufferedReader(new InputStreamReader(_instream), 4000);
17
18 try
19 {
20 String line;
21 final StringBuilder builder = new StringBuilder(DEFAULT_BUFFER_SIZE);
22 while ((line = reader.readLine()) != null)
23 {
24 builder.append(line);
25 }
26 return builder;
27
28 }
29 finally
30 {
31 close(reader);
32 }
33
34 }


hth,
Mac

Windmate HD, See you @ IO 14 , Worked on Wundercar, Glass V3, LG G Watch, Moto 360, Android TV

Antworten
Dominic Bartl
  • Forum-Beiträge: 180

21.06.2010, 22:27:27 via Website

Ich hab mir mal diese nützliche klasse geschrieben:

[code]
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.Log;


public class ExternalStorageManager {

private File externalStorage;

private boolean isExternalStorageAvailable = false;
private boolean isExternalStorageWriteable = false;


public ExternalStorageManager() {
externalStorage = Environment.getExternalStorageDirectory();
checkExternalStorageAvailability();
}

public boolean canRead(){
return isExternalStorageAvailable;
}

public boolean canWrite(){
return isExternalStorageWriteable;
}

public boolean exist(String path){
return (canRead() && (new File(externalStorage, path).exists()));
}

public void makeDir(String path){
if(canWrite()){
File make = new File(externalStorage, path);
make.mkdirs();
}
}

public void makeDirIfNotExist(String path){
if(!exist(path)){
makeDir(path);
}
}

public void write(String path, String file, String text){
try {
if (externalStorage.canWrite()){
File tmpfile = new File(externalStorage, path+file);
FileWriter writer = new FileWriter(tmpfile);
BufferedWriter out = new BufferedWriter(writer);
out.write(text);
out.close();
}
} catch (IOException e) {
Log.e("ExternalStorageManager", "Could not write file " + e.getMessage());
}
}

public String[] read(String path, String filename){
try{
ArrayList<String> tmpList = new ArrayList<String>();
File f = new File(externalStorage, path+filename);
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));

String l = "";
while((l = buf.readLine())!= null){
tmpList.add(l);
}
String [] r = new String[tmpList.size()];
for(int i = 0; i < tmpList.size(); i++){
r[i] = tmpList.get(i);
}
return r;

} catch (FileNotFoundException e) {
Log.e("ExternalStorageManager", "Cant find file " + externalStorage + path + filename);
} catch (IOException e){
Log.e("ExternalStorageManager", "IOException while reading " + externalStorage + path + filename);
}
return null;

}

public String[] readDirectory(String path){
File dir = new File(externalStorage, path);
return dir.list();
}

public File[] getFileList(String path){
String[] names = readDirectory(path);
File[] files = new File[names.length];
for (int i = 0; i < names.length; i++) {
files[i] = new File(externalStorage, path+names[i]);
}
return files;
}

public void deleteFile(String path){
new File(externalStorage,path).delete();
}

private void checkExternalStorageAvailability(){

String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
isExternalStorageAvailable = isExternalStorageWriteable = true;
Log.i("ExternalStorageManager", "We can read and write the media");
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
Log.i("ExternalStorageManager", "We can only read the media");
isExternalStorageAvailable = true;
isExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
isExternalStorageAvailable = isExternalStorageWriteable = false;
}
}

}

[/code]

— geändert am 21.06.2010, 22:28:54

Antworten
Alex W.
  • Forum-Beiträge: 84

22.06.2010, 17:24:39 via Website

Wow, da hast Du ja an alles gedacht :-) Not bad.

Btw, mit dem hier hab ichs dann hinbekommen:

fis = openFileInput(FILENAME);
String line;
DataInputStream dis = new DataInputStream(fis);
while((line=dis.readLine())!=null)
Log.v("Outp", line);
myText = myText+line;

.....



usw...

Antworten