I am new to android development. I've tried to write a file with a number in my android device . I could store the file in internal storage but I couldn't write on this file at this time.
This is my code .
Have any suggestions reveal to me.
int count=0;
FileOutputStream outputStream;
BufferedReader input=null;
File file=new File(getCacheDir(),"example.txt");
if(file.exists()==true){
try {
input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
StringBuilder builder=new StringBuilder();
while((line=input.readLine())!=null){
builder.append(line);
}
String g=builder.toString();
Toast.makeText(getApplicationContext(),"Count - " + g,Toast.LENGTH_LONG).show();
}catch (IOException e){
}
}else {
try {
count=count+1;
outputStream = new FileOutputStream(file);
outputStream.write(count);
outputStream.close();
Toast.makeText(getApplicationContext(),"File - "+file.getPath().toString(),Toast.LENGTH_LONG).show();
}catch (IOException e){
Toast.makeText(getApplicationContext(),"Error creating this file",Toast.LENGTH_LONG).show();
}
}
Thanks
Add this line in Your AndroidManifest.xml File
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Thanks everyone , I found a solution for my problem. I can do above work using a Sting instead of a integer. See you soon bye.
Related
i am trying to read file from internal storage. the file is available in internal storage at given location and the code is able to access it.. but when it tries to open the file , it throws FileNotFound Exception which is due to the app can't open the file to read. I came to know about the app can't open the file by using file.canRead() method which is returning false. can anybody help me to figure the situation out? Here is my code
path = MainActivity.this.getFilesDir().getAbsolutePath();
try {
File file = new File(path, "jamshaid.txt");
Context ctx = getApplicationContext();
FileInputStream fileInputStream = ctx.openFileInput(file.getName());
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String lineData = bufferedReader.readLine();
view1.setText(lineData);
} catch (Exception e) {
e.printStackTrace();
}
Permissions
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
API Version of my device is 24
What i wanna do?
i am trying to parsethe file/set text file data to textView
Update1
after changing
File directory = MainActivity.this.getFilesDir();
File file = new File(directory, "jamshaid.txt");
i am getting the following error
`09-25 14:45:16.413 21144-21144/com.example.root.testingvolley W/System.err: java.io.FileNotFoundException: /data/user/0/com.example.root.testingvolley/files/jamshaid.txt (No such file or directory)`
Try this for directory path
File directory = context.getFilesDir();
File file = new File(directory, filename);
Or
public String getTextFileData(String fileName) {
StringBuilder text = new StringBuilder();
try {
FileInputStream fIS = getApplicationContext().openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIS, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
text.append(line + '\n');
}
br.close();
} catch (IOException e) {
Log.e("Error!", "Error occured while reading text file from Internal Storage!");
}
return text.toString();
}
How are you verifying that the file exists? Perhaps the file does not exist, in which case openFileInput() will throw FileNotFoundException.
You can try opening the file in write-mode which will create a file if no such file exists.
FileOutputStream fileOutputStream = ctx.openFileOutput(file.getName(), ctx.MODE_PRIVATE);
I am a beginner when it comes to Android. I encountered a problem, regarding writing to a file. I want to save to a file the input I get in a form. However, the piece of code that I wrote is not writing in my file. Could anyone please help me?
The code looks like that:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder s = new StringBuilder();
s.append("Event name: " + editText1.getText() + "|");
s.append("Date: " + editText2.getText() + "|");
s.append("Details: " + editText3.getText() + "|");
File file = new File("D:\\config.txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024);
out.write(s.toString());
out.newLine();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
So, I have a form containing 3 fields: the name of an event, the date and the description. These I want to save to my file. I should mention that I use an emulator for testing.
Use following path for file. It will write file to your root folder of storage.
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");
writeToFile("File content".getBytes(), file);
writeToFile
public static void writeToFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
Don't forget to add following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
https://github.com/rznazn/GPS-Data-Logger/blob/master/app/src/main/java/com/example/android/gpsdatalogger/StorageManager.java
Here is a... nearly complete class for writing to the documents folder on the emulated external storage of the device.
Don't forget to add the write permissions to manifest.
Within my app I am trying to write a file, which I can then internally read from.
Would anyone have an example of how to write files to the installation folders of app?
use the following code to write from Edittext into file and read from file into Edittext
set the following permission to AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
JAVA CODE
EditText LoadedText;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadedText=(EditText) findViewById(R.id.LoadedText);
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File("/sdcard/RouterSetup.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');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
LoadedText.setText(text.toString());
}
public void saveFile() {
try {
File myFile = new File("/sdcard/RouterSetup.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(LoadedText.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD " + LoadedText.getText() + ".txt",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
getFilesDir() vs Environment.getDataDirectory()
public File getFilesDir ()
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
public static File getExternalStorageDirectory ()
Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().
If you want to get your application path use getFilesDir() which will give you path /data/data/your package/files
You can get the path using the Environment var of your data/package using the
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath(); which will return the path from the root directory of your external storage as /storage/sdcard/Android/data/your pacakge/files/data
To access the external resources you have to provide the permission of WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
The simplest solution is
String filename = "stuff.xml";
READ
FileInputStream stream = ctx.openFileInput(filename);
(and below is a really simple example of parsing that file)
BufferedReader buffReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = buffReader.readLine()) != null) {
...
// do something cool
...
}
} catch (IOException e) {
Log.e("MyApp", "SCREAAAAAM", e);
}
WRITE
OutputStreamWriter outputStreamWriter = new OutputStreamWriter( ctx.openFileOutput(filename, Context.MODE_PRIVATE) );
outputStreamWriter.write("this is text not xml :(");
So the two main things to note are the openFileInput and openFileOutput methods of Context (ie your activity) which take care of the heavy lifting
//here i am downloading file from server and writing
String download_link = "some server location";
URL url = new URL(download_link);
HttpsURLConnection c = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
c = (HttpsURLConnection) url.openConnection();
c.setHostnameVerifier(DO_NOT_VERIFY);
}
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "Mobi.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
you need to add permission in manifest file:
uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
Which type of files you are talking about ?
For data storage you can use shared preferences.
For media type you can use media storage.
I am trying to open the sdcard's .txt file in my EditText to change the text in it and
save the changes using button click but its not going in right way .May I know what is the correct way to achieve my objective?
try this one..
you must set permission in the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "followed by ur file dir");
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "sdcard.txt");
for (File wavfile : f.listFiles())
{
String str = wavfile.getName().toString();
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/sdcard/"+filename);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
edtitext.setText(aBuffer.tostring());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext
(),aBuffer,Toast.LENGTH_LONG).show();
}
}
again btnclick you have to write that edited string right..
use this one for write in that file..
FileOutputStream fos;
try {
File myFile = new File("/sdcard/"+sdcard.txt);
myFile.createNewFile();
FileOutputStream fOut = new
FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new
OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(),filename + "
saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
thank you...
more detalis ref this link'
http://www.javatpoint.com/android-external-storage-example
----------------------------------------------------------
Some manufacturers (mainly Samsung) give write permissions only to the internal storage mounted at /storage/sdcard.
Also you should enable your app to write to external storage by adding this permission in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
First try to read the complete text file and save the text in a string.
For that you can refer this link
When you read the complete text file and get the text in a string, set the string to the editText by
edtitext.setText(your string);
I am not having luck with this method, which is basically a hello world for printing file contents to the Android cat log.
try {
InputStream instream = openFileInput("inputFile.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
while (( line = buffreader.readLine()) != null) {
System.out.println(line);
}
instream.close();
} catch (java.io.FileNotFoundException e) {
e.printStackTrace();
}
Using a default generated project with the Android Eclipse plugin, under what directory should this file exist? Any other considerations?
This will try to read the file inputFile.txt from your internal application data directory /data/data/your.application.package/ (and will fail if it doesn't exist):
openFileInput("inputFile.txt");
To read a file from SD card you would do something like this:
new FileInputStream(Environement.getExternalStorageDirectory()
.getAbsolutePath() + "/inputFile.txt")
Don't forget to set the SD card permission in your manifest then:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This file should exist in the apps local 'data' directory. Does this file already exist? Have you taken a look at the documentation for file IO on Android?