Read internal file java

Android Read Write Internal Storage File Example

Android data can be saved in internal storage ( ROM ), external storage(SD card), shared preferences, or SQLite database. This article will introduce how to read and write data in internal storage via a java file.

1. Android Read Write Data To Internal File.

  1. Android is based on Linux, the android file system is Linux-based also.
  2. Android studio provides the android device monitor tool for you to monitor and transfer files between Android devices and your PC. Please refer Android Device Monitor Cannot Open Data Folder Resolve Method.

1.1 Where Your Android App Internal Data File Saved In?

  1. All android app internal data files are saved in the /data/data/ folder.
  2. In this example, my app data internal file is saved in /data/data/com.dev2qa.example folder. You can watch the youtube video https://youtu.be/AJBgBBMKO5w to see the android app’s internal data files saved directory.
  3. From the youtube video, we can see that there are files and cache subfolders under the package name folder.
  4. files folder — android.content.Context’sgetFilesDir() method can return this folder. This folder is used to save general files.
  5. cache folder — android.content.Context’sgetCacheDir() method can return this folder. This folder is used to save cached files.
  6. When the device’s internal storage space is low, cache files will be removed by android os automatically to make internal storage space bigger. Generally, you need to delete the unused cache files in the source code timely, the total cache file size is better not more than 1 MB.

1.2 Read Write Android File Code Snippets.

  1. Android application is written in java, so the file operation uses java classes also.
  2. Below are the code snippets for read/write data from/to the file in android.
1.2.1 Read Android File In The Package files Folder.
  1. Call android.content.Context‘s openFileInput(userEmalFileName) method to get FileInputStream object.
  2. The input parameter is just the file name.
  3. This file should be saved in the files folder.
  4. Then use the FileInputStream object to read data.
Context ctx = getApplicationContext(); FileInputStream fileInputStream = ctx.openFileInput(userEmalFileName); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String lineData = bufferedReader.readLine();
1.2.2 Read Android File In The Package cache Folder.
File file = new File(getCacheDir(), userEmalFileName); FileInputStream fileInputStream = new FileInputStream(file);
1.2.3 Write File To The Package files Folder.
  1. Method 1: Use Context’s getFilesDir() to get the package files folder, then write file into it.
File file = new File(getFilesDir(), userEmalFileName); FileOutputStream fileOutputStream = new FileOutputStream(file); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); bufferedWriter.write(data);
FileOutputStream fileOutputStream = ctx.openFileOutput(userEmalFileName, Context.MODE_PRIVATE);
1.2.4 Write File To The Package cache Folder.
File file = new File(getCacheDir(), userEmalFileName); FileOutputStream fileOutputStream = new FileOutputStream(file);

2. Android Internal File Operation Example.

  1. You can watch the example demo video on youtube https://youtu.be/HqbRR6TQVvY.
  2. There are one input text box and five buttons on the android example app main screen.
  3. The buttons’ function can be easily understood by the button’s label text.
  4. The button’s label text is WRITE TO FILE, READ FROM FILE, CREATE CACHED FILE, READ CACHED FILE, CREATE TEMP FILE from up to bottom.
  5. After you run the example, you can see the below files in the android device monitor. You can pull down the file to your local PC to see the file contents also.
com.dev2qa.example/cache/customCache.txt com.dev2qa.example/cache/temp175008654.txt com.dev2qa.example/files/userEmail.txt

2.1 Layout XML File.

2.2 Activity Java File.

package com.dev2qa.example.storage.file; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.dev2qa.example.R; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class WriteReadFileActivity extends AppCompatActivity < private String TAG_WRITE_READ_FILE = "TAG_WRITE_READ_FILE"; private String userEmalFileName = "userEmail.txt"; private String cacheFileName = "customCache.txt"; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_write_read_file); setTitle("dev2qa.com - Android Read Write Internal Storage File Example."); final EditText editText = (EditText)findViewById(R.id.write_read_file_edit_text); // Write to internal file button. Button writeToFileButton = (Button)findViewById(R.id.write_to_file_button); writeToFileButton.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < String userEmail = editText.getText().toString(); if(TextUtils.isEmpty(userEmail)) < Toast.makeText(getApplicationContext(), "Input data can not be empty.", Toast.LENGTH_LONG).show(); return; >else < Context ctx = getApplicationContext(); /* This comments code can also write data to android internal file. File file = new File(getFilesDir(), userEmalFileName); writeDataToFile(file, userEmail); */ try < FileOutputStream fileOutputStream = ctx.openFileOutput(userEmalFileName, Context.MODE_PRIVATE); writeDataToFile(fileOutputStream, userEmail); >catch(FileNotFoundException ex) < Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); >Toast.makeText(ctx, "Data has been written to file " + userEmalFileName, Toast.LENGTH_LONG).show(); > > >); // Read from internal file. Button readFromFileButton = (Button)findViewById(R.id.read_from_file_button); readFromFileButton.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < try < Context ctx = getApplicationContext(); FileInputStream fileInputStream = ctx.openFileInput(userEmalFileName); String fileData = readFromFileInputStream(fileInputStream); if(fileData.length()>0) < editText.setText(fileData); editText.setSelection(fileData.length()); Toast.makeText(ctx, "Load saved data complete.", Toast.LENGTH_SHORT).show(); >else < Toast.makeText(ctx, "Not load any data.", Toast.LENGTH_SHORT).show(); >>catch(FileNotFoundException ex) < Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); >> >); // Write to internal cache file button. Button createCachedFileButton = (Button)findViewById(R.id.create_cached_file_button); createCachedFileButton.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < String userEmail = editText.getText().toString(); if(TextUtils.isEmpty(userEmail)) < Toast.makeText(getApplicationContext(), "Input data can not be empty.", Toast.LENGTH_LONG).show(); return; >else < File file = new File(getCacheDir(), cacheFileName); writeDataToFile(file, userEmail); Toast.makeText(getApplicationContext(), "Cached file is created in file " + cacheFileName, Toast.LENGTH_LONG).show(); >> >); // Read from cache file. Button readCacheFileButton = (Button)findViewById(R.id.read_cached_file_button); readCacheFileButton.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < try < Context ctx = getApplicationContext(); File cacheFileDir = new File(getCacheDir(), cacheFileName); FileInputStream fileInputStream = new FileInputStream(cacheFileDir); String fileData = readFromFileInputStream(fileInputStream); if(fileData.length()>0) < editText.setText(fileData); editText.setSelection(fileData.length()); Toast.makeText(ctx, "Load saved cache data complete.", Toast.LENGTH_SHORT).show(); >else < Toast.makeText(ctx, "Not load any cache data.", Toast.LENGTH_SHORT).show(); >>catch(FileNotFoundException ex) < Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); >> >); // Write to internal temp file button. Button createTempFileButton = (Button)findViewById(R.id.create_temp_file_button); createTempFileButton.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < try < String userEmail = editText.getText().toString(); if(TextUtils.isEmpty(userEmail)) < Toast.makeText(getApplicationContext(), "Input data can not be empty.", Toast.LENGTH_LONG).show(); return; >else < // This method will create a temp file in android cache folder, // temp file prefix is temp, suffix is .txt, each temp file name is unique. File tempFile = File.createTempFile("temp", ".txt", getCacheDir()); String tempFileName = tempFile.getAbsolutePath(); writeDataToFile(tempFile, userEmail); Toast.makeText(getApplicationContext(), "Temp file is created, file name is " + tempFileName, Toast.LENGTH_LONG).show(); >>catch(IOException ex) < Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); >> >); > // This method will write data to file. private void writeDataToFile(File file, String data) < try < FileOutputStream fileOutputStream = new FileOutputStream(file); this.writeDataToFile(fileOutputStream, data); fileOutputStream.close(); >catch(FileNotFoundException ex) < Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); >catch(IOException ex) < Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); >> // This method will write data to FileOutputStream. private void writeDataToFile(FileOutputStream fileOutputStream, String data) < try < OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); bufferedWriter.write(data); bufferedWriter.flush(); bufferedWriter.close(); outputStreamWriter.close(); >catch(FileNotFoundException ex) < Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); >catch(IOException ex) < Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); >> // This method will read data from FileInputStream. private String readFromFileInputStream(FileInputStream fileInputStream) < StringBuffer retBuf = new StringBuffer(); try < if (fileInputStream != null) < InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String lineData = bufferedReader.readLine(); while (lineData != null) < retBuf.append(lineData); lineData = bufferedReader.readLine(); >> >catch(IOException ex) < Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); >finally < return retBuf.toString(); >> >

3. Question & Answer.

3.1 Can not write text file to android internal storage.

  1. My android app is very simple, I just want to write some text to a file and save the text file to the internal storage. I follow this article to write source code, but I can not find the text file in both the android physical device and the simulator. I can not read the file content out in java source code. Can you tell me why? Thanks a lot.
  2. Android 11 has announced a new policy when you want to manage storage. The internal storage root folder can not be used to store files unless you add the below permission in your AndroidManifest.xml file.

And when you run the application, you can request this permission to the user with the below code.

requestPermissions(new String[], 1);

Источник

How to read a File in Java

How to read a File in Java

In this article, you’ll learn how to read a text file or binary (image) file in Java using various classes and utility methods provided by Java like BufferedReader , LineNumberReader , Files.readAllLines , Files.lines , BufferedInputStream , Files.readAllBytes , etc.

Let’s look at each of the different ways of reading a file in Java with the help of examples.

Java read file using BufferedReader

BufferedReader is a simple and performant way of reading text files in Java. It reads text from a character-input stream. It buffers characters to provide efficient reading.

import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class BufferedReaderExample  public static void main(String[] args)  Path filePath = Paths.get("demo.txt"); Charset charset = StandardCharsets.UTF_8; try (BufferedReader bufferedReader = Files.newBufferedReader(filePath, charset))  String line; while ((line = bufferedReader.readLine()) != null)  System.out.println(line); > > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Java read file line by line using Files.readAllLines()

Files.readAllLines() is a utility method of the Java NIO’s Files class that reads all the lines of a file and returns a List containing each line. It internally uses BufferedReader to read the file.

import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class FilesReadAllLinesExample  public static void main(String[] args)  Path filePath = Paths.get("demo.txt"); Charset charset = StandardCharsets.UTF_8; try  ListString> lines = Files.readAllLines(filePath, charset); for(String line: lines)  System.out.println(line); > > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Java read file line by line using Files.lines()

Files.lines() method reads all the lines from a file as a Stream . You can use Stream API methods like forEach , map to work with each line of the file.

import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FilesLinesExample  public static void main(String[] args)  Path filePath = Paths.get("demo.txt"); Charset charset = StandardCharsets.UTF_8; try  Files.lines(filePath, charset) .forEach(System.out::println); > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Java read file line by line using LineNumberReader

LineNumberReader is a buffered character-stream reader that keeps track of line numbers. You can use this class to read a text file line by line.

import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class LineNumberReaderExample  public static void main(String[] args)  Path filePath = Paths.get("demo.txt"); Charset charset = StandardCharsets.UTF_8; try(BufferedReader bufferedReader = Files.newBufferedReader(filePath, charset); LineNumberReader lineNumberReader = new LineNumberReader(bufferedReader))  String line; while ((line = lineNumberReader.readLine()) != null)  System.out.format("Line %d: %s%n", lineNumberReader.getLineNumber(), line); > > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Java read binary file (image file) using BufferedInputStream

All the examples presented in this article so far read textual data from a character-input stream. If you’re reading a binary data such as an image file then you need to use a byte-input stream.

BufferedInputStream lets you read raw stream of bytes. It also buffers the input for improving performance.

import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; public class BufferedInputStreamImageCopyExample  public static void main(String[] args)  try(InputStream inputStream = Files.newInputStream(Paths.get("sample.jpg")); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); OutputStream outputStream = Files.newOutputStream(Paths.get("sample-copy.jpg")); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream))  byte[] buffer = new byte[4096]; int numBytes; while ((numBytes = bufferedInputStream.read(buffer)) != -1)  bufferedOutputStream.write(buffer, 0, numBytes); > > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Java read file into []byte using Files.readAllBytes()

If you want to read the entire contents of a file in a byte array then you can use the Files.readAllBytes() method.

import com.sun.org.apache.xpath.internal.operations.String; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesReadAllBytesExample  public static void main(String[] args)  try  byte[] data = Files.readAllBytes(Paths.get("demo.txt")); // Use byte data > catch (IOException ex)  System.out.format("I/O error: %s%n", ex); > > >

Источник

Читайте также:  Deep dive into python
Оцените статью