Use of FileInputStream utility class and FileInputStream class for Android data storage

  • 2020-11-03 22:34:52
  • OfStack

Android's three typical native ways of storing data

SharedPreferences

Save in file format in local storage

SQL database

This article is about how to save files using SharedPreferences. The main explanation is written in the notes.

IDE : Android Studio

Refer to the article: https: / / www ofstack. com article / 74215. htm

Verbose 1: The original document operation 1 piece last week to understand it, and then continue to learn 1 step further. But the concepts in the official Android Training are too complex. Which leads me to think that storing it internally is going to query the space, get a return and so on. The result is that I confused the idea of saving an internal space (the file folder under the package name in the data directory) with an external space (storage space). So it takes a lot of time and it doesn't work. Finally see the reference article just know how to write. Then he followed the reference article over 1 times.

Again, I used a separate approach, which is to create a tool class that is modular and easy to use. Hope to help others, but also to establish a concept of their own.

Without further ado, the code above:


import android.content.Context;
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* Created by zhizhao on 2015/11/1 0001 in 16:00.
*/
public class UsingFileInputStream {
private Context fileContext;
private String fileName;
private String fileUserName;
private String filePassword;
public UsingFileInputStream(String name, Context context, String userName, String password) {
this.fileName = name;
this.fileContext = context;
this.fileUserName = userName;
this.filePassword = password;
}
// When saved, it is written continuously to the contents of the file, that is, it is written again based on the data saved previously. 
public void writeFileInputStream() {
try {
FileOutputStream fileOutputStream = fileContext.openFileOutput(fileName,
fileContext.MODE_PRIVATE);
byte[] byteUserName = fileUserName.getBytes();
byte[] bytePassword = filePassword.getBytes();
fileOutputStream.write(byteUserName);
fileOutputStream.write(bytePassword);
Log.v("FileInputStream Save the result  ", "UserName = " + fileUserName + " Password = " + filePassword);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// To read a file is to read the entire contents of a file. If parsing is to be added, save it in a special format. 
public void readFileInputStream() {
try {
FileInputStream fileInputStream = fileContext.openFileInput(fileName);
int len = fileInputStream.available();
byte[] buffer = new byte[len];
fileInputStream.read(buffer);
Log.v(" The file read is: ", ""+new String(buffer));
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Here is how to use:


private void writeFile(){
UsingFileInputStream fileInputStream = new UsingFileInputStream("account",
MySaveDataActivity.this, userName, userPass);
fileInputStream.writeFileInputStream();
tvReadInformation.setText(" Save successfully! " + "\n UserName = " + userName + "\n UserPass = " + userPass);
}
private void readFile(){
UsingFileInputStream fileInputStream = new UsingFileInputStream("account",
MySaveDataActivity.this, userName, userPass);
fileInputStream.readFileInputStream();
tvReadInformation.setText(" Read successfully! "+"\n UserName = "+userName+"\n UserPass = "+userPass);
}

Conclusion 1:

I don't think what I've written so far is quite right. It's perfect. Because the filename is filled in repeatedly during the call, the value is passed in. And it's hard to know if it was a success or failure in the return value.

Moreover, I did not catch and operate on the file exception, because if there is no file to operate on, there will be an error: null pointer exception.

However, since this is an exercise, I did not consider that much, because this time just in try{}catch(){} code block to add their own means of operation.

Now I have a little bit of time to take you through the use of the Android FileInputStream class

1. FileInputStream class overview

Inheritance relationship:

java.io.FileInputStream- > java.io.InputStream- > java.lang.Object

Implementation interface:

Closeable

Class functions:

FileInputStream gets the input bytes from a file in the file system. Which files are available depends on the host environment.

FileInputStream is used to read raw byte streams such as image data. To read character streams, consider using FileReader.

2. Properties and behavior of classes

(1) public void close() throws IOException

Functions: Close this file input stream and release all system resources associated with this stream.

If this flow has a channel associated with it, close the channel.

Specified by: close in interface Closeable

Override: close in class InputStream

Thrown: IOException - If an I/O error occurs.

(2) public int read() throws IOException

Function: Read 1 byte of data from this input stream. If no input is available, this method blocks.

Specifies: read in class InputStream

Return: The next data byte; If the end of the file has been reached, -1 is returned.

Thrown: IOException - If an I/O error occurs.

(3) public int read(byte[] b) throws IOException

Function: Reads up to ES138en.es139EN bytes of data into a 1-byte array from this input stream. This method will block until some input is available

Override: read in class InputStream

Parameter: b - the buffer that stores the read data

Returns: The total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.

Thrown: IOException - If an I/O error occurs.

(4) public int read(byte[] b, int off, int len) throws IOException

Function: Reads up to len bytes of data into a 1-byte array from this input stream. This method blocks until some input is available.

Override: read in class InputStream

Parameter: b - The buffer that stores the read data.

off - The initial offset of the data.

len - Maximum number of bytes read.

Returns: The total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.

Thrown: IOException - if an I/O error occurs.

3. Common mistakes

Using FileInputStream under eclipse, you are prompted that the specified file cannot be found

Code:


 filename = "abc.txt" ;
  FileInputStream fis = new FileInputStream(filename);

Error display:


 java.io.FileNotFoundException: dbconfig.properties ( The system could not find the specified file. )
  at java.io.FileInputStream.open(Native Method)
  at java.io.FileInputStream.<init>(FileInputStream.java:106)
  at java.io.FileInputStream.<init>(FileInputStream.java:66)

Solutions:

Because when main runs the main program under eclipse, eclipse will automatically put the publication directory as its root directory, so it will prompt you to change filename to absolute directory instead of finding the file

filename = "\sdcard\...\abc.txt" ;


Related articles: