New to Java. Problems reading from file using Context and openFileInput - java

I've been trying to do this on my own for the past couple hours and am kinda losing it a little.
All I want to do is open a file, read it and display it to the console; that's it.
I'm using eclipse to develop for android 2.3.3.
I have tried using a bunch of different ways with code that I have found here, and on other sites. Here is what I have now and how its all called:
In the OnCreate function:
setContentView(new TestMap(this));
The testMap class:
TestMap(Context context){
super(context);
// might need to be on the panel class
loadTileFile("worldonelayout.txt", context);
in the same class:
private void loadTileFile (String filename, Context context){
FileInputStream input = null;
InputStreamReader reader = null;
char[] inputBuffer = new char[256];
String data = null;
try {
input = context.openFileInput("worldonelayout.txt");
reader = new InputStreamReader(input);
reader.read(inputBuffer);
data = new String(inputBuffer);
System.out.println(data);
Toast.makeText(context, "Text read", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Text not read", Toast.LENGTH_SHORT).show();
} finally {
try {
input.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code doesnt work. It always hits the exception.
"/data/data/com.name.somethingiremoved/files/worldonelayout.txt (No such file or directory)".
This happens at the first CATCH. BTW my file is in the root directory: Documents\Eclipse\workspace\project\worldonelayout.txt. I can also see the file in the browser on the left
From what I have seen here and on other sites, it is something to do with the Context class being derived from the Activity? I don't want to have this code in the same class as my activity. Is there a way round this?
If you need anything more from me, let me know.

The open file is looking for a file on the phone's file system, not on the computer's. Its telling you exactly where it expects to find it - on the phone under /data/data/com.name.somethingiremoved/files/worldonelayout.txt

Related

Android Studio - Read and Write to/from file in local storage within a folder

So I'm trying to read and write to and from a file that is inside a folder within the app's directory. So the path is something like "package/userFiles/'insert file name here'" but I can't find a way to do it anywhere.
I haven't been able to test this yet but the below is the code I've got for writing a quick and simple string to the file. If you could take a look over that I would be grateful, and if at all possibly give me some direction over how to read from the file.
FileOutputStream outputStream;
File path = new File(getFilesDir(),"userFiles");
path.mkdirs();
File mypath =new File(path,newFileNameText);
try {
FileOutputStream out = new FileOutputStream(mypath);
String defaultMessage = "Empty File";
out.write(defaultMessage.getBytes());
out.close();
Intent intent = new Intent(getApplicationContext(), EditFileContents.class);
intent.putExtra(EXTRA_MESSAGE,newFileNameText);
startActivity(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can see the code starts a new activity, it is this activity from which I would like to be able to read the contents of the file.

Saving a file on the internal storage of android using Context

I'm trying to save a random hello world file onto the internal storage of my android. When I run my app, it simply stops.
Code:
public void saveDataOnDevice(String toWrite, String filename) {
Context ctx = null;
try {
FileOutputStream fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(toWrite.getBytes());
fos.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
Another question is, what Context means. I read a lot about this here, but I still don't get it.
First of all... your context is null always: Context ctx = null;, so you wont be able to make it work in any way.
To simplify: Context, in a simple app, will be your MainActivity. In a bigger app, you can have several contexts and answer will be more complex.
Back to your code, if it is placed inside your MainActivity context will be this:
public void saveDataOnDevice(String toWrite, String filename) {
try {
FileOutputStream fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
// ^ --> refers to main class, in this case your MainActivity
fos.write(toWrite.getBytes());
fos.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
NOTE: if you don't have this method inside the MainActivity, you must pass a reference of your Activity to the method or the class somehow (attribute, method param, etc..etc...).
Check Android Developers::saving files for further info.

Displaying Base64-Encoded String of raw PDF data using ThinkFree PDF Viewer

The problem:
I'm getting a Base64-Encoded String of raw PDF data from a web service (this data is housed in my String array pdfData). I have to use this data display the PDF in a PDF viewer (I happen to be using the included 'ThinkFree PDF Viewer' since I'm working on an Android application, but lets generalize and say any PDF viewer will do). Note that I'm accessing the 0th element of this array just for testing purposes (to make sure I can at least pull up 1 PDF before writing the code to pull up all the PDFs).
The code is within a class. First the method createFile is called, then intentOpenPDF:
import org.apache.commons.codec.binary.Base64;
File file;
FileOutputStream outputStream;
private byte[] decodedContent;
private String[] pdfData;
private String[] pdfFileName;
public void createFile() {
decodedContent = Base64.decodeBase64(pdfData[0].getBytes());
try {
File path = new File(getFilesDir(), "PDFs");
if (!path.exists()) {
path.mkdirs();
}
file = new File(path, pdfFileName[0]);
outputStream = new FileOutputStream(file);
outputStream.write(decodedContent);
outputStream.close();
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
// Make absolutely certain the outputStream is closed
try {
if (outputStream != null) {
outputStream.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void intentOpenPDF() {
// Make sure the file exists before accessing it:
if (file.exists()) {
Uri targetUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
The error:
Error opening file. It does not exist or cannot be read.
I have a break point set inside the conditional statement that checks if the file exists (within the intentOpenPDF method), and it IS passing this check.
The path produced by calling getFilesDir() leads a protected directory (file:///data/data/), where only files created with openFileOutput(String, int) are stored. I am not creating the file this way. The solution in my case is to use getExternalFilesDir(null).getAbsolutePath() instead, which will give you a path a directory internal to the application (/storage/emulated/0/Android/data/). No permissions are required to read or write to this path.
Considering your error message:
It does not exist or cannot be read.
as you verified it exists (first possible cause), it's certainly not readable (second possible cause).

De-Serializing StreamCorrupted

I have a a problem I have been dealing with for quite some time now. When attempting to de-serialize my custom "Sound" objects in a folder I continue to get 3 exceptions. IOException, NullPointerException, and StreamCorruptedException. Please take a look:
Method for reading sounds:
public static Sound readSound(String loc){
try{
FileInputStream fis = new FileInputStream(loc);
ObjectInputStream ois = new ObjectInputStream(fis);
fis.close();
ois.close();
return (Sound)ois.readObject();
}catch(Exception e){
System.out.println("Failed to read a serialized object.");
e.printStackTrace();
return null;
}
}
Exceptions/Errors Received: http://gyazo.com/b53faa9590adf6448bf14db11f275325
(Too much to paste here and it pastes incorrectly)
Loading the sounds:
(add sound just adds the sound to an ArrayList as well as a JComboBox)
private static File saveDirFile = new File("/Users/francisj12/Desktop/ACData/");
private static File saveDirFileSounds = new File(saveDirFile.getPath()+"/sounds/");
public static void loadAllSounds(){
if(!saveDirFile.exists()){
saveDirFile.mkdir();
}
if(!saveDirFileSounds.exists()){
saveDirFileSounds.mkdir();
}
for(int x=0; x<saveDirFileSounds.list().length; x++){
try{
File sndFl = new File(saveDirFileSounds.listFiles()[x].getPath());
Sound newSound = Serialize.readSound(sndFl.getPath());
addSound(newSound);
}catch(Exception e){
e.printStackTrace();
continue;
}
}
}
Here it what the .ser files look like: (Once I started using transient on variables so I could serialize my custom Sound object which I dont understand transient yet, it started making the .ser look as follows instead of a ton of weird characters its just one line of weird characters now)
¨ÌsrAlarms.SoundË.®ŸÓÓxp
Hope this is all the information you guys will need thanks so much for your help!

Why do I get FileNotFoundException when I create and try to write to file on Android emulator?

First off, I am not trying to write to the SDCard. I want to write some information to a file that persists between uses of the app. It is essentially a file to hold favorites of the particular user. Here is what the code looks like:
try {
File file = new File("favorites.txt");
if (file.exists()) {
Log.d(TAG, "File does exist.");
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
}
else {
Log.d(TAG, "File does not exist.");
return favDests;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
When running this code, we always get the "File does not exist." message in our DDMS log.
We have also tried the following code to no avail:
try {
File file = new File(GoLincoln.FAV_DEST_FILE);
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It is this second portion of code that results in the FileNotFoundException.
I have read multiple tutorials on writing and reading files on Android and I believe I am following them pretty closely, so I am not sure why this code doesn't work successfully. I appreciate any help!
You shouldn't use the File class directly. Use Activity.getCacheDir() to get the cache dir which is specific to your application. Then use new File(cachedir, "filename.tmp") to create the file.
Preferences and SQLLite will both allow you to have persistent data without managing your own files.
To use shared preferences you grab it from your context, then you edit the values like so
mySharedPreferences = context.getSharedPreferences("DatabaseNameWhateverYouWant", 0);
mySharedPreferences.getEditor().putString("MyPreferenceName", "Value").commit();
To get a preference out
mySharedPreferences.getString("MyPreferenceName", "DefaultValue");
This is really the simplest way to do basic preferences, much easier then doing a file. More then strings are supported, most basic data types are available to be added to the Preferences class.

Categories