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()
Related
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
I have a arrays of apk files, what I need is to do write the apk files of ArrayList into cache storage and read it back again as same ArrayList. I know how to insert a single file and retrieve back again from the cache. But whereas ArrayList objects as concern I completely stuck up with the solutions and methodology. Please help me. I am using following code for read and write into cache memory. Any modification or slight changes in my code will be more helpful to me. Thanks in advance
Actual code for Read and write single File
//Write to cache dir
FileWriter writer = null;
try {
writer = new FileWriter(tmpFile);
writer.write(text.toString());
writer.close();
// path to file
// tmpFile.getPath()
} catch (IOException e) {
e.printStackTrace();
}
//Read to cache directory
String TMP_FILE_NAME = "base.apk";
File tmpFile;
File cacheDir = getBaseContext().getCacheDir();
tmpFile = new File(cacheDir.getPath() + "/" + TMP_FILE_NAME) ;
String line="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tmpFile);
BufferedReader bReader = new BufferedReader(fReader);
while( (line=bReader.readLine()) != null ){
text.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
Modified code for my requirement to insert ArrayList<File>
String tempFile = null;
public void writeFile(ArrayList<File> files(){
for(File file: files) {
FileWriter writer = null;
try {
writer = new FileWriter(file);
tempFile = file.getName().toString();
writer.write(file.getName().toString());
writer.close();
// path to file
// tmpFile.getPath()
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is where I stuck completely to read as ArrayList
What i tried is
String line="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tempFile);
BufferedReader bReader = new BufferedReader(fReader);
while( (line=bReader.readLine()) != null ){
text.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
I found my own answer for my question after a longstruggle from the blog.
To Write a ArrayList<File>:
public static void createCachedFile (Context context, String key, ArrayList<File> fileName) throws IOException {
String tempFile = null;
for (File file : fileName) {
FileOutputStream fos = context.openFileOutput (key, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream (fos);
oos.writeObject (fileName);
oos.close ();
fos.close ();
}
}
To Read a ArrayList<File>
public static Object readCachedFile (Context context, String key) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput (key);
ObjectInputStream ois = new ObjectInputStream (fis);
Object object = ois.readObject ();
return object;
}
Final code in my Activity
createCachedFile (MainActivity.this,"apk",adapter.getAppList ());
ArrayList<File> apkCacheList = (ArrayList<File>)readCachedFile (MainActivity.this, "apk");
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;
}
I want to read a text file that i had write in another activity using OutputStreamWriter.
this is my readFromFile method in Sale.java:
private int readFromFile(String request) {
int res = 0;
try {
//InputStream inputStream = openFileInput("dalassnums.txt");
File file=new File("dalassnums.txt");
InputStream inputStream = new FileInputStream(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null ) {
String s=bufferedReader.readLine();
if(receiveString==request) {
res=Integer.valueOf(s);
break;
}
}
inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
res=0;
} catch (IOException e) {
//Log.e("login activity", "Can not read file: " + e.toString());
}
return res;
}
And this is writeToFile method in MainActivity.java:
private void writeToFile2(String numchar) {
try {
//File file=new File("dalassnums.txt");
//OutputStream outputStream=new FileOutputStream(file);
OutputStreamWriter outputStreamWriter;
if(numchar=="1") outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_PRIVATE));
else outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_APPEND));
for(int k=0; k<imageNums.size();k+=2){
outputStreamWriter.append(imageNums.get(k));
outputStreamWriter.append("\n");
outputStreamWriter.append(imageNums.get(k+1));
outputStreamWriter.append("\n");
}
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
When performing readFromFile, it returns 0 that means file not found;
I read about passing context but i don't know what context to pass; And wondering if there is any other way than passing context.
Any help would be appreciated.
Use : openFileInput in readFromFile, look here for example:
openFileInput() and/or openFileOutput() i/o streams silently failing
Another problem is that this is invalid:
if(numchar=="1")
you should
if(numchar.equals("1"))
otherwise you compare reference values instead content of string
I have an utility class named 'MyClass'. The class has two methods to read/write some data into phone's internal memory. I am new to android, Please follow below code.
public class MyClass {
public void ConfWrite() {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
while executing ConfWrite method, it fails
please provide a better solution to solve this
thanks in advance
You can Read/ Write your File in data/data/package_name/files Folder by,
To Write
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
To Read
BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(getFilesDir()+File.separator+"MyFile.txt")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = bufferedReader.readLine()) != null){
builder.append(read);
}
Log.d("Output", builder.toString());
bufferedReader.close();
public static void WriteFile(String strWrite) {
String strFileName = "Agilanbu.txt"; // file name
File myFile = new File("sdcard/Agilanbu"); // file path
if (!myFile.exists()) { // directory is exist or not
myFile.mkdirs(); // if not create new
Log.e("DataStoreSD 0 ", myFile.toString());
} else {
myFile = new File("sdcard/Agilanbu");
Log.e("DataStoreSD 1 ", myFile.toString());
}
try {
File Notefile = new File(myFile, strFileName);
FileWriter writer = new FileWriter(Notefile); // set file path & name to write
writer.append("\n" + strWrite + "\n"); // write string
writer.flush();
writer.close();
Log.e("DataStoreSD 2 ", myFile.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readfile(File myFile, String strFileName) {
String line = null;
try {
FileInputStream fileInputStream = new FileInputStream(new File(myFile + "/" + strFileName)); // set file path & name to read
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // create input steam reader
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) { // read line by line
stringBuilder.append(line + System.getProperty("line.separator")); // append the readed text line by line
}
fileInputStream.close();
line = stringBuilder.toString(); // finially the whole date into an single string
bufferedReader.close();
Log.e("DataStoreSD 3.1 ", line);
} catch (FileNotFoundException ex) {
Log.e("DataStoreSD 3.2 ", ex.getMessage());
} catch (IOException ex) {
Log.e("DataStoreSD 3.3 ", ex.getMessage());
}
return line;
}
use this code to write --- WriteFile(json); // json is a string type
use this code to read --- File myFile = new File("sdcard/Agilanbu");
String strObj = readfile(myFile, "Agilanbu.txt");
// you can put it in seperate class and just call it where ever you need.(for that only its in static)
// happie coding :)