Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android FileInputStream read() txt file to String

Tags:

java

android

io

Any experts available to help me? In my Android main activity, I'm trying to save a String to a file and then retrieve it if the user has set it before. Wasn't able to find any examples close to what I am doing. I would most appreciate any help! Here is my test case that crashes:

String testString = "WORKS"; String readString;  @Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.main);      FileOutputStream fos;      try {         fos = openFileOutput("test.txt", Context.MODE_PRIVATE);         fos.write(testString.getBytes());         fos.close();     } catch (FileNotFoundException e) {         e.printStackTrace();      } catch (IOException e) {         e.printStackTrace();      }      File file = getBaseContext().getFileStreamPath("test.txt");      if (file.exists()) {          FileInputStream fis;          try {             fis = openFileInput("test.txt");             fis.read(readString.getBytes());             fis.close();          } catch (IOException e) {             e.printStackTrace();          }           txtDate.setText(String.valueOf(readString));         } else {                      // more code        }      }  } 
like image 692
jbearden Avatar asked Feb 01 '12 12:02

jbearden


People also ask

How do I read a file with FileInputStream?

The FileInputStream class reads the data from a specific file (byte by byte). It is usually used to read the contents of a file with raw bytes, such as images. First of all, you need to instantiate this class by passing a String variable or a File object, representing the path of the file to be read.

What does the read () method of FileInputStream return?

The read() method of a FileInputStream returns an int which contains the byte value of the byte read.

How do I read a file into a String?

The readString() method of File Class in Java is used to read contents to the specified file. Return Value: This method returns the content of the file in String format. Note: File. readString() method was introduced in Java 11 and this method is used to read a file's content into String.

How do you specify a file path in FileInputStream?

This String should contain the path in the file system to where the file to read is located. Here is a code example: String path = "C:\\user\\data\\thefile. txt"; FileInputStream fileInputStream = new FileInputStream(path);


1 Answers

For reading file try this:

FileInputStream fis; fis = openFileInput("test.txt"); StringBuffer fileContent = new StringBuffer("");  byte[] buffer = new byte[1024];  while ((n = fis.read(buffer)) != -1)  {    fileContent.append(new String(buffer, 0, n));  } 
like image 95
user370305 Avatar answered Sep 27 '22 17:09

user370305