I'm developing an app in which I'm sending a .txt file from one end by attaching it with gmail. Everytime this file is sent, its name is data.txt. When this file is downloaded at the other end, on the first download its name is the same, i.e. data.txt. However, when another file is sent with the same name, the name of the file at the receiveing end becomes data-1.txt, data-2.txt etc. And because of this, I'm not able to read the proper file. Please could someone give me some suggestions to solve this problem? The sending and receiving code is given below: SEND
bSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
String toWrite = enterText.getText().toString();
FileOutputStream fos;
try {
String path = Environment.getExternalStorageDirectory().toString();
Log.v("path", path);
File myFile = new File("" + path + "/" + fileName + ".txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(toWrite);
Log.v("file written", toWrite);
myOutWriter.close();
fOut.close();
Uri u1 = null;
u1 = Uri.fromFile(myFile);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "MPPT Configuration Data");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
READ:
bRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/storage/sdcard0/download/" + fileName + ".txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
Log.v("read data", "" + aBuffer);
tvData.setText(aBuffer);
}catch (IOException e2) {
e2.printStackTrace();
}
}
});
I found a possible solution. I can link the file manager (external app) from where the user can pick out whichever file he wants to be read.
Thanks #greenapps fir the idea of displaying a list of files.
You can get all the file by using regex ,then process the file by following way:
1.if only one file found,read it;
2.if more than one file found, compare and read the file which last number is biggest
but this solution still has one problem,if has file data.txt and data-3.txt ,the file we want to read may become data-2.txt,but what we really read is data-3.txt.
Or,maybe you can get the file you want by judging file established time.
Related
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.
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 generating a notification for classes according to my timetable. In the notification i am providing action button if the user clicks this button a file for that class opens where attendance is marked for the corresponding class. I have written the following code
public class Record extends BroadcastReceiver
{public void onReceive(Context context, Intent intent)
{
String f = intent.getStringExtra("class");
String fname= f+".txt";
System.out.println("File Name :" + fname);
try
{ File name = new File(f+".txt");
if(!name.exists())
{
System.out.println("Creating file" + fname);
name.createNewFile();
FileOutputStream fos = context.openFileOutput(fname,Context.MODE_PRIVATE);
String str1= "1";
fos.write(str1.getBytes());
fos.close();
if(!name.exists())
{
System.out.println("FILE NOT CREATED");
}
}
else
{ String inputString;
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
context.openFileInput(fname)));
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null)
{
stringBuffer.append(inputString + "\n");
}
int number = Integer.parseInt(inputString);
number=number+1;
String str1 = String.valueOf(number);
FileOutputStream fos = context.openFileOutput(fname,Context.MODE_PRIVATE);
fos.write(str1.getBytes());
fos.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
So what i did is check if the file exists . if not then create one else increment the contents by one.
when i run this and click on the action button, i get
1) File Name
2) Creating File
but don't get FILE NOT CREATED. this means the file is being created. But i cannot find the file in DDMS view.
I dont know where i am going wrong. Please help.
It is probably already created. Context.MODE_PRIVATE automatically creates the file in your internal app directory if not already there. The complete path to your internal app files directory is /data/data/com.example.yourpackage/files.
Is your phone rooted? Because you shouldn't be able to see the root folders in DDMS without it being rooted. If so, another way you can check is use a File Manager program on your phone. I use ES File Manager.
Try to put fname on the disk as I doubt that you are creating file in a non authorized area on the disk
Use
String fname= getFilesDir() +"/" + f+".txt";
I am using this code as a part to write data to a text file, but I am not sure how I can append the data to the new line. "\n" does not seem to be working. Here, variable "data" has this format:
t=1, x=-3.1, y=19.0, z=-8.6
this part of the code iterates and the variable "data" is written each time; the current result is something like:
t=1, x=-6.9, y=-9.6, z=-6.9t=2, x=-1.4, y=6.2, z=7.0t=3, x=-1.4, y=6.1, z=6.9t=4, and so on, but what I would like is:
t=1, x=-6.9, y=-9.6, z=-6.9
t=2, x=-1.4, y=6.2, z=7.0
t=3, x=-1.4, y=6.1, z=6.9
Thanks in advance for your help.
String datatest = data.toString();
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/test");
directory.mkdirs();
String filename = "test.txt";
File file = new File(directory, filename);
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(datatest + "\n");
osw.flush();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
try "\r\n"
and to make this answer longer :)
I'm saving a file to a non-default spot in Android and am trying to be able to open it to load information from it but cannot find a way to specify the path to the file...
Here is how I am saving the file...
File directory = new File(path + "/Android/data/com.etechtour/save_data/");
directory.mkdirs();
extStorageDirectory = path.toString() + "/Android/data/com.etechtour/save_data/";
File file = new File(extStorageDirectory, "pumpItUpGas.txt");
try
{
outStream = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(outStream);
out.write("Record#: " + record + ", Nickname: " + nickname + ", Year: " + year + ", Make: " + make + ", Model: " + model);
out.flush();
out.close();
outStream.flush();
outStream.close();
}
Now I've successfully saved the file to this location, but when trying to access it I can't figure out ANYTHING that works to set the path to load the file. I've looked around everywhere online and can't seem to find anything that works except using the default save position. Here's how I'm trying to load but am either forceclosing or getting null pointer exceptions
try
{
String filename = Environment.getExternalStorageDirectory().toString() + "/Android/data/com.etechtour/save_data/pumpItUpGas.txt";
InputStream in = openFileInput("pumpItUpGas.txt");
//FileReader fileReader = new FileReader(file);
//FileInputStream fileInput = new FileInputStream(path);
if (in != null)
//if (fileReader != null)
{
InputStreamReader temp = new InputStreamReader(in);
//InputStreamReader tmp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(temp);
StringBuffer buf = new StringBuffer();
while ((str = reader.readLine()) != null)
{
buf.append(str);
}
//fileInput.close();
in.close();
return str;
}
}
Any help would be greatly appreciated. Thanks
Use FileInputStream or FileReader with your File object, just like normal Java I/O.