I am having an issue where I am trying to create a file locally on the android emulator however when I test it the file exists, it doesn't. I do not have access to a physical android device so am using the emulator.
Please note I do not want to save the file on the SD card. I am not very familiar with android's file structure so forgive me if my code doesn't make sense.
This is the code I am currently using and it doesn't work :(
EditText editText = (EditText) findViewById(R.id.editTextName);
String sName = editText.getText().toString();
editText = (EditText) findViewById(R.id.editTextEmail);
String sEmail = editText.getText().toString();
editText = (EditText) findViewById(R.id.editTextPostal);
String sPostal = editText.getText().toString();
File file = new File("/storage/new/test.txt");
FileOutputStream fos;
byte[] data = new String("Name: " + sName + " Subject: " + sEmail + " Question: " + sPostal ).getBytes();
OutputStream myOutput;
try {
myOutput = new BufferedOutputStream(new FileOutputStream(file,true));
myOutput.write(data);
myOutput.flush();
myOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(file.exists())
{
finish();
}
Could anyone experienced enough in the area of android development provide me with some sample code or point me in the right direction so I can get this bad boy working?
EDIT: When I say it doesn't work, I mean the file never gets created.
If you are new to file storage in Android I suggest you read trough this piece of documentation to get started - it should answer your questions with examples.
Related
In my android app, I am putting values to a text file and I have confirmed that it works. I can open the text file on my android device and see ALL of the data in there as it should be. However, when I plug the device into my PC via USB, some of the data in the text file gets cut off.
Here's the data I see on my android device when I open the text file:
false,false,false,NULL,NULL,false,false,NULL,NULL,60,67,false,true,1,false,4,1,
Here's the data I see when I access the text file on my computer:
false,false,false,NULL,NULL,false,false,NULL,NULL,60,67,false,true,1,f
As you can see, the last few pieces of data get cut off. I've tried with different data and it still gets cut off there.
I'm not sure if this will help as the following code seemingly does get all the data to the text file (if looking on my android device), but here's the code for writing to the text file. I'm getting two lists of data from SharedPreferences files I've previously created and writing them to a file when a button is pressed.
SharedPreferences auto = getSharedPreferences("Auto", MODE_PRIVATE);
SharedPreferences teleop = getSharedPreferences("Teleop", MODE_PRIVATE);
autoValues = auto.getAll();
teleopValues = teleop.getAll();
public void writeToFile(View view){
try {
FileOutputStream stream = new FileOutputStream(myFile);
for (Map.Entry<String, ?> entry : autoValues.entrySet()){
stream.write(entry.getValue().toString().getBytes());
stream.write(",".getBytes());
}
for (Map.Entry<String, ?> entry : teleopValues.entrySet()){
stream.write(entry.getValue().toString().getBytes());
stream.write(",".getBytes());
}
stream.close();
System.out.println("SUCCESS: MAY HAVE WRITTEN TO FILE IN EXPORT");
} catch (Exception e){
e.printStackTrace();
System.out.println("ERROR: DID NOT WRITE TO FILE");
}
}
Use following function to efficiently write to your file. You must have permission to access external storage.
public static void logToFile(String message) {
String formattedData = String.format("%s", (new SimpleDateFormat("dd-MM HH:mm:ss", Locale.getDefault())
.format(new Date())) + "\t\t\t" + message + "\n");
FileOutputStream stream = null;
String path = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DOWNLOADS;
try {
File file = new File(path + "/Logger.txt");
if (!file.exists()) {
file.createNewFile();
}
stream = new FileOutputStream(file, true);
stream.write(formattedData.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
I want to save text from my app that can be opened from various devices (phones, tablets, computers, ect) and after doing research I figured a docx would be the best choice. I need to have the text be monospaced so a simple .txt file would not work. I noticed though that when I save this file and try to open it up using QuickOffice or POLARIS or any other office type application on my phone or tablet I get a message "Unsupported file". I can open it in office using my computer but I get a message saying that I need to select an encoding. Is there a way in my program either by setting the fontFamily or something similar to remedy this?
I'm under the assumption that it is saving using whatever the default font is for Android and that font doesn't exist in these other applications so it does not recognize it. But I could be wrong. Any help would be appreciated! This is my code for saving: (I should note that string1(2)(3) come from a TextView
private void saveResults() {
SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss", Locale.getDefault());
String timeStamp = format.format(new Date());
String filename = timeStamp + "_Results.docx";
CharSequence fileOutput = "Results:\n" + string1 + "\n" + string2 + "\n\n" +
string3;
if(isExternalStorageWritable()){
try{
File file = new File(Environment.getExternalStorageDirectory(), filename);
file.createNewFile();
FileOutputStream fileOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fileOut);
myOutWriter.append(fileOutput);
myOutWriter.close();
fileOut.close();
Toast.makeText(getBaseContext(),
"Saved " + filename + " to " + Environment.getExternalStorageDirectory(),
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getBaseContext(), "Cannot write to external storage", Toast.LENGTH_SHORT).show();
}
}
I have 3 different process running and wanted to collect logs from them on to a single log file, using logcat.
Is it possible this logfile to have logs only from my 3 processes ? How to do the same programitcally.
any help regarding the same highly appreciated.
-regards,
Manju
you can try this way call this method and put put your message what you write in log file and is stored in your sd card. Any where your application tested it will create a log and you can see the details
public static void MyLog(String msg_location, String log_message) {
String messgae_location = msg_location;
String message_details = log_message;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath()
+ "/mydata/LOG");
if (!dir.exists()) {
dir.mkdirs();
}
BufferedWriter bufferedWritter = null;
try {
bufferedWritter = new BufferedWriter(new FileWriter(dir
+ File.separator + "my_Log.txt", true));
String logString = null;
logString = currentDateTime1() + ": " + messgae_location + ": "
+ message_details + "\n";
bufferedWritter.write(logString);
bufferedWritter.newLine();
bufferedWritter.flush();
} catch (FileNotFoundException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
}
}
You can filter the logcat output by tags.
You can use regular expressions when filtering. E.g. if you have 3 tags tag1m tag2, tag3 then if your filter is tag1|tag2 you will see logcaat output tagged by tag1 and tag2 (but not tag3).
To log your messages in a file better use Log4j for android. It's also simple.
i am saving video and image in a folder ..now i want to make this folder as password protected , means while opening this folder needs to enter a password for view the file inside it
hope here ill get any relevant answer for doing this...if there some any other possible please suggest..
try {
dirName = "/mydirectory/";
fileName = new Long(
SystemClock.currentThreadTimeMillis())
.toString()
+ ".png";
} catch (NullPointerException e) {
// TODO: handle exception
}
try {
if (android.os.Environment
.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED)) {
File sdCard = Environment
.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath()
+ dirName);
dir.mkdirs();
File file = new File(storedImagePath);
os = new FileOutputStream(file, true);
byte[] byteArray = receivedImageData.getBytes();
byteArray = Base64.decode(byteArray, 0);
os.write(byteArray);
os.flush();
os.close();
} else {
}
} catch (Exception e) {
}
I'd like to suggest a different/feasible approach, Encrypt your file!
Look at this answer!
Even if you are successful in implementing a password protection (Wow!) here are the cons,
This will only protect when your app is running.
SD cards are supposed to be transferred(Hence your app cannot protect the files on SDcard always).
This question already has an answer here:
I need to be able to store sound files for my application on sdcard
(1 answer)
Closed 2 years ago.
I found this code which appears to be what I need in that it will copy byte for byte a file to the SDCard.
But how do I use it? say I have a text file called mytext.txt where do I put it in my application? and how would I reference it? I am using Eclipse
public static final void copyfile(String srFile, String dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied to " + f2.getAbsolutePath());
} catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch(IOException e){
System.out.println(e.getMessage());
}
}
I would make a FileUtilities class or somesuch. Have you looked at the examples here?
http://download.oracle.com/javase/tutorial/essential/io/copy.html
http://www.java2s.com/Code/Java/File-Input-Output/FileCopyinJava.htm
You don't want to blindly execute this code. It looks like it's meant for a java console app. System Printlines do not go anywhere that the user would see in an android application. I do not know what System.exit() does in an Android application, but you don't want to do this either. Depending on your application, you may want to add a toast notification that a copy fails. You want to at least log this.
Depending on the size of files you are copying, you may want to do this in a background thread as to not clog up your UI.
Well, at first glance that appears to be a sound method, except that you'd want to replace the System.out print statements with an android Log method... but besides that you could copy/paste that and include that method in a class.
To use it, however... you should have a look at the External Storage documentation.
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
You're going to need to use Android methods to get correct sdcard directories, etc...
You can add it as another method of your own Activity if your code is small, or you can create a utility class, let's suppose
class MyUtilities {
public static final void copyfile(String srFile, String dtFile) throws IOException, FileNotFoundException{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
Log.d("MyUtilities", "File copied to " + f2.getAbsolutePath());
}
}
and you will use it as:
TextEdit text1 = findViewById(R.id.text1);
TextEdit text2 = findViewById(R.id.text2);
String file1 = text1.getText();
String file2 = text2.getText();
if (text1 != null and text2 != null) {
try{
MyUtilities.copyfile (file1, file2);
} catch(FileNotFoundException ex){
Log.e("MyUtilities", ex.getMessage() + " in the specified directory.");
} catch(IOException e){
Log.e("MyUtilities", e.getMessage());
}
}
I added logs instead of the System.out and changed the Exception mechanism to better match android needs.