FileInputStream doesn't access the file [duplicate] - android

I have a resource file in my /res/raw/ folder (/res/raw/textfile.txt) which I am trying to read from my android app for processing.
public static void main(String[] args) {
File file = new File("res/raw/textfile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Do something with file
Log.d("GAME", dis.readLine());
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried different path syntax but always get a java.io.FileNotFoundException error. How can I access /res/raw/textfile.txt for processing? Is File file = new File("res/raw/textfile.txt"); the wrong method in Android?
***** Answer: *****
// Call the LoadText method and pass it the resourceId
LoadText(R.raw.textfile);
public void LoadText(int resourceId) {
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Note this will return nothing, but will print the contents line by line as a DEBUG string in the log.

If you have a file in res/raw/textfile.txt from your Activity/Widget call:
getResources().openRawResource(...) returns an InputStream
The dots should actually be an integer found in R.raw... corresponding to your filename, possibly R.raw.textfile (it's usually the name of the file without extension)
new BufferedInputStream(getResources().openRawResource(...)); then read the content of the file as a stream

Related

How to read a text file from a Class method

I want to use a Class method to read a text file & pass a return value.
My error is the line:
fis = openFileInput(FILE_NAME);
The error message is:
Cannot resolve method 'openFileInput(java.lang.String)'
I suspect it's because I'm not passing a context, or that Android does not know the full file path using my Class method code.
I want to use the Class method so I can call it from various Activities.
import java.io.FileInputStream;
public static String GetUserId(){
String str_return = null;
String FILE_NAME = "userid.txt";
try {
FileInputStream fis = null;
fis = openFileInput(FILE_NAME); \\<-- error is here
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
} catch (FileNotFoundException e) {
//e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try this :
File yourFile = new File("YOUR_TEXTFILE_PATH");
String data = null;
try (FileInputStream stream = new FileInputStream(yourFile)) {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
data = Charset.defaultCharset().decode(bb).toString(); //this is the data from your textfile
} catch (Exception e) {
e.printStackTrace();
}
And generating the textfile
File root = new File("YOUR_FOLDER_PATH");
//File root = new File(Environment.getExternalStorageDirectory(), folderName); //im using this
//creation of folder (if you want)
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, textFileName);
FileWriter writer;
writer = new FileWriter(gpxfile);
writer.append(textFileData);
writer.flush();
writer.close();
}
I have done it in one of my kotlin project likethis, It might work in Java too.
val textFromFile = openFileInput(filePath).reader().readText()

Download a file with an AsyncTask

I tried using many codes I've found for downloading files with an AsyncTask with no success yet.
I get an error on the logcat: E/Error:: No such file or directory.
Despite looking for solutions for this error, couldn't find What's missing or wrong.
This is the doInBackground method in which I assume something is missing/wrong:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new DownloadJSON().execute("http://api.androidhive.info/json/movies.json");
}
protected String doInBackground(String...fileUrl) {
int count;
try {
String root = "data/data/com.example.jsonapp2";
URL url = new URL(fileUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File fileName = new File(root+"/movies.json");
boolean existsOrNot = fileName.createNewFile(); // if file already exists will do nothing
// Output stream to write file
OutputStream output = new FileOutputStream(fileName,false);
byte data[] = new byte[1024];
System.out.println("Downloading");
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
Thanks.
Didn't want to bombard with redundant code. If some other code is needed, I'd love to provide it.
UPDATED ANSWER
this is working for me, write file in local storage and read it again on method PostExecute
class DownloadJSON extends AsyncTask<String, Void, Void>{
String fileName;
String responseTxt;
String inputLine;
String folder;
#Override
protected Void doInBackground(String... strings) {
try {
String root = "data/data/com.example.jsonapp2";
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//Set methods and timeouts
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
urlConnection.connect();
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder response = new StringBuilder();
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
response.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
responseTxt = response.toString();
Log.d(TAG, "doInBackground: responseText " + responseTxt);
// PREPARE FOR WRITE FILE TO DEVICE DIRECTORY
FileOutputStream fos = null;
fileName = "fileName.json";
folder = fileFolderDirectory();
try {
fos = new FileOutputStream(new File(folder + fileName));
//fos = openFileOutput(folder + fileName, MODE_PRIVATE);
fos.write(responseTxt.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
fos.close();
}
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// -- THIS METHOD IS USED TO ENSURE YOUR FILE AVAILABLE INSIDE LOCAL DIRECTORY -- //
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(folder +fileName));
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
Toast.makeText(TestActivity.this, "result " + sb.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ops, almost forget this method
public static String fileFolderDirectory() {
String folder = Environment.getExternalStorageDirectory() + File.separator + "write_your_app_name" + File.separator;
File directory = new File(folder);
if(!directory.exists()){
directory.mkdirs();
}
return folder;
}
Your root is wrong
String root = "data/data/package.appname";
make sure your root contains right package name or file path.
package name which should be your application id

Convert input stream into file android

in my application i am using below code that returns input stream
QBContent.downloadFileById(fileId, new QBEntityCallback<InputStream>() {
#Override
public void onSuccess(final InputStream inputStream, Bundle params) {
long length = params.getLong(Consts.CONTENT_LENGTH_TAG);
Log.i(TAG, "content.length: " + length);
// use inputStream to download a file
}
#Override
public void onError(QBResponseException errors) {
}
}, new QBProgressCallback() {
#Override
public void onProgressUpdate(int progress) {
}
});
now i want to covert input steam into file then want to do two things with that file
1. how can i save it to user's phone storage
2. save it temporarily and display's it in pdf viewer using intent
note: returned file will be in pdf formal
You did not mentionned if you wanted to store in external or internal storage, I wrote this example for internal storage
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("file.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(total.toString());
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
Don't forget to use try/catch and close what needs to be closed
You can use below code to store InputStream in File.
But you need to pass file path and where you want to store file in storage.
InputStream inputStream = null;
BufferedReader br = null;
try {
// read this file into InputStream
inputStream = new FileInputStream("/Users/mkyong/Downloads/file.js");
br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
System.out.println("\nDone!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to return file object from assets in Android?

I want to return file object from assests folder. In Similar questions's response, it's returned InputStream class object, but I don't want to read content.
What I try to explain, there is an example.eg file in assests folder. I need to state this file as File file = new File(path).
Try this:
try {
BufferedReader r = new BufferedReader(new InputStreamReader(getAssets().open("example.csv")));
StringBuilder content = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
content(line);
}
} catch (IOException e) {
e.printStackTrace();
}
As far as I know, assets are not regular accessible files like others.
I used to copy them to internal storage and then use them.
Here is the basic idea of it:
final AssetManager assetManager = getAssets();
try {
for (final String asset : assetManager.list("")) {
final InputStream inputStream = assetManager.open(asset);
// ...
}
}
catch (IOException e) {
e.printStackTrace();
}
You can straight way create a file using InputStream.
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}

Adding file contents to an ArrayList; Android

What I am trying to accomplish is to read a file line by line and store each line into an ArrayList. This should be such a simple task but I keep running into numerous problems. At first, it was repeating the lines when it was saved back into a file. Another error which seems to occur quite often is that it skips the try but doesn't catch the exception? I have tried several techniques but no luck. If you have any advice or could provide help in anyway it would be greatly appreciated. Thank you
Current code:
try{
// command line parameter
FileInputStream fstream = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
fileList.add(strLine);
}
//Close the input stream
in.close();
} catch (Exception e){//Catch exception if any
Toast.makeText(this, "Could Not Open File", Toast.LENGTH_SHORT).show();
}
fileList.add(theContent);
//now to save back to the file
try {
FileWriter writer = new FileWriter(file);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
There is a very simple alternative to what you are doing with Scanner class:
Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
s.close();
Why do you have fileList.add(theContent) after the try/catch? I don't see what the point of that is. Remove that line and see if it helps.
Example, I just tested this code on my local machine (not android but should be the same)
import java.io.*;
import java.util.ArrayList;
class FileRead
{
public static void main(String args[])
{
ArrayList<String> fileList = new ArrayList<String>();
final String file = "textfile.txt";
final String outFile = "textFile1.txt";
try{
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
fileList.add(strLine);
}
//Close the input stream
in.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
try {
FileWriter writer = new FileWriter(outFile);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
System.err.println("Error: " + error.getMessage());
}
}
}
After I ran this the 2 files had no differences. So my guess is that line may have something to do with it.

Categories

Resources