I just wanna create a text file into phone memory and have to read its content to display.Now i created a text file.But its not present in the path data/data/package-name/file name.txt & it didn't display the content on emulator.
My code is..
public class PhonememAct extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=(TextView)findViewById(R.id.tv);
FileOutputStream fos = null;
try {
fos = openFileOutput("Test.txt", Context.MODE_PRIVATE);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fos.write("Hai..".getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = openFileInput("Test.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int c;
try {
while((c=fis.read())!=-1)
{
tv.setText(c);
setContentView(tv);
//k += (char)c;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks in adv.
You don't need to use input/output streams if you are simply trying to write/read text.
Use FileWriter to write text to a file and BufferedReader to read text from a file - it's much simpler. This works perfectly...
try {
File myDir = new File(getFilesDir().getAbsolutePath());
String s = "";
FileWriter fw = new FileWriter(myDir + "/Test.txt");
fw.write("Hello World");
fw.close();
BufferedReader br = new BufferedReader(new FileReader(myDir + "/Test.txt"));
s = br.readLine();
// Set TextView text here using tv.setText(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
//To read file from internal phone memory
//get your application context:
Context context = getApplicationContext();
filePath = context.getFilesDir().getAbsolutePath();
File file = new File(filePath, fileName);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
return text.toString(); //the output text from file.
This may not be an answer to your question.
I think, you need to use the try-catch correctly.
Imagine openFileInput() call fails, and next you are calling fos.write() and fos.close() on a null object.
Same thing is seen later in fis.read() and fis.close().
You need to include openFileInput(), fos.write() and fos.close() in one single try-catch block. Similar change is required for 'fis' as well.
Try this first!
You could try it with a stream.
public static void persistAll(Context ctx, List<myObject> myObjects) {
// save data to file
FileOutputStream out = null;
try {
out = ctx.openFileOutput("file.obj",
Context.MODE_PRIVATE);
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(myObjects);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is working fine for me like this. Saving as text shouldn't be that different, but I don't have a Java IDE to test here at work.
Hope this helps!
Related
public void loadprev()
{
String tempread;
try {
FileInputStream fis = openFileInput("data.gds");
try {
fis.read(tempread.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
my program crashes upon trying to execute fis.read(tempread.getBytes());
i want to read the first line in data.gds and put it into a string, how can i do this?
and no, im not going to use SharedPreferences
add a string buffer and then read from it everyline will be put in the Stringbuffer, then you can retrieve the line from that buffer.
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while ((n = fis.read(buffer)) != -1)
{
fileContent.append(new String(buffer, 0, n));
}
Also, if you are not catching exceptions properly, surround them in 1 try catch, but try to catch them in the future:
{
String tempread;
try {
FileInputStream fis = openFileInput("data.gds");
fis.read(tempread.getBytes());
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
now your code is easier to read.
I want to read in the data from a csv-file and store it into a database. This is how I saved the csv-file (this works without errors - just to show where and how the file is stored which I plan to read with CSVreader):
synchronized public void readFromUrl(String url, String outputFile, Context context) throws FileNotFoundException {
URL downloadLink = null;
try {
downloadLink = new URL(url);
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader(downloadLink.openStream(), "UTF8"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileOutputStream fstream = context.openFileOutput(outputFile,Context.MODE_PRIVATE);
Writer out = new OutputStreamWriter(fstream);
Log.d(TAG, "BufferedReader "+in);
String inputLine = null;
try {
while ((inputLine = in.readLine()) != null){
out.write(inputLine+"\n");
//logger.debug("DOWNLOADED: "+inputLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fstream.close();
out.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My code so far for reading the csv file:
public void readInCSVFile(String filename, Context context) throws IOException {
IDbHelper dbHelper = new DbHelper(); ;
CSVReader products = null;
products = new CSVReader(new InputStreamReader(context.getAssets().open(filename)));
I get a NoClassDefFoundError exception.
I have the opencsv.jar in the Referenced libraries of my android project.
Thanks in advance for your help.
Is your project in the Eclipse IDE? If yes, then have a look whether the lib (opencsv.jar) is set in the "project properties->Java Build Path->Libraries" and that it is checked in the tab: "Order and Export" too. Under "Order and Export" move the lib to the top of the list.
Then clean and rebuild.
PS: If this does not help, then please provide the complete stacktrace of the error.
I am able to write and then read a text file in the SAME activity, but I am unable to read a text file after writing to it from another Activity.
Ex: Activity A creates and writes to a text file. Activity B reads that text file.
I use this code to write to the text file in Activity A:
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try
{
fos = openFileOutput("user_info.txt", Context.MODE_WORLD_WRITEABLE);
osw = new OutputStreamWriter(fos);
osw.write("text here");
osw.close();
fos.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And then I use this code to try and read the same text file created by Activity A, but I get a FileNotFoundException:
try
{
FileInputStream fis = openFileInput("user_info.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader buff = new BufferedReader(isr);
String line;
while((line = buff.readLine()) != null)
{
Toast.makeText(this, line, Toast.LENGTH_LONG).show();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Does anyone know why I am getting the FileNotFoundException?
Is it a path issue?
Don't really know how is built your application, but, the error you get does seem like a path issue, are you sure both Activities are in the same folder ?
If not, you'll need to set either an abolute path (like : "/home/user/text.txt") for the text file or a relative path (like : "../text.txt").
If you're not sure, try to print the current path for the Activity using some command like
new File(".").getAbsolutePath();
And, although I can't say I'm expert with Android, are you sure you need the Context.MODE_WORLD_WRITEABLE for your file ? If no other application than yours is reading or writing from/to it, it should not be necessary, right ?
it is surealy a path issue.
you can write like this
fpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory";
File custdir=new File(fpath);
if(!custdir.exists())
{
custdir.mkdirs();
}
File savedir=new File(custdir.getAbsolutePath());
File file = new File(savedir, filename);
if(file.exists())
{
file.delete();
}
FileOutputStream fos;
byte[] data = texttosave.getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
Toast.makeText(getBaseContext(), "File Saved", Toast.LENGTH_LONG).show();
finish();
} catch (FileNotFoundException e) {
Toast.makeText(getBaseContext(), "Error File Not Found", Toast.LENGTH_LONG).show();
Log.e("fnf", ""+e.getMessage());
// handle exception
} catch (IOException e) {
// handle exception
Toast.makeText(getBaseContext(), "Error IO Exception", Toast.LENGTH_LONG).show();
}
and you can read like
String locatefile=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory"+"/filename";
try {
br=new BufferedReader(new FileReader(locatefile));
while((text=br.readLine())!=null)
{
body.append(text);
body.append("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OKay so I'm handling Files where I ask user Input and my program updates the Spinner with new selection.
Here's the codes for write:
public void writeOnFile(String string){
try {
FileOutputStream file = openFileOutput(fileName, Context.MODE_APPEND);
file.write(string.getBytes());
file.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and read:
public void readOnFile(){
try {
FileInputStream file = openFileInput(fileName);
if(file!=null){
InputStreamReader inputreader = new InputStreamReader(file);
BufferedReader buffreader = new BufferedReader(inputreader);
String course;
while((course = buffreader.readLine()) != null){
adapter.add(course);
}
}
file.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and here's bit of my spinner's code:
courseSpinner = (Spinner) findViewById(R.id.courseSpinner);
adapter = new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
readOnFile();
adapter.add("The Country Club");
courseSpinner.setAdapter(adapter);
When I update the Spinner instead of seeing two selections which is "course 1" and "course" 2
I see one selection with the text "course 1course 2" :/
How do I fix this?
Since you are interpreting the strings as separated by newline, you need to write each of the strings to new line in the file.
Change your write code to:
public void writeOnFile(String string){
try {
FileOutputStream file = openFileOutput(fileName, Context.MODE_APPEND);
file.write(string.getBytes());
file.write("\n".getBytes());
file.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I'm trying to read from a text file under /data/data/package_name/files.
This is my code:
private String readTxt(String fileName)
{
String result = "", line;
try
{
File f = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
while((line = br.readLine()) != null)
{
result += line + "\n";
}
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
What am I doing wrong?
You should use the openFileInput Method from your application context. http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
Which will give you a InputStream to your file
Example:
final InputStream is = getApplicationContext().openFileInput(MY_FILENAME_WITHOUT_PATH);
private String getStringFromFile(Context accessClass,String fileName){
String result=null;
FileInputStream fIn;
ContextWrapper accessClassInstance=new ContextWrapper(accessClass);
try {
fIn = accessClassInstance.openFileInput(fileName);
InputSource inputSource=new InputSource(fIn);
InputStream in = inputSource.getInputStream();
if (in != null) {
// prepare the file for reading
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
result = "";
while (( line = buffreader.readLine()) != null) {
result += line;
}
in.close();
Toast.makeText(getApplicationContext(),"File Contents ==> " + result,Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}