So I'm trying to basically write some logs to a text file so i can view it later. I'm running this on a physical phone, not the emulator. I've tried so many different variations, and the most i got was it writing to data/data and storage/emulated but i can never access my file. Any help would be appreciated. Some of my latest undeleted examples have been:
String filename = "myfile.txt";
try {
File path = new File(context.getFilesDir(), "myfolder");
if (!path.exists())
path.mkdir();
File output = new File(path, filename);
BufferedWriter buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
Log.d("Success",
"Successfully wrote a file " + context.getFilesDir());
} catch (Exception e) {
e.printStackTrace();
}
and
final String appPath = String.format("%s/Datafiles",
context.getFilesDir());
File path = new File(appPath);
if (!path.exists()) {
path.mkdir();
}
String fileName = String.format("%s/filedemo.txt", appPath);
and
try {
String filename = "myfile.txt";
File path = new File(Environment.getRootDirectory(), "myfolder");
if (!path.exists())
path.mkdir();
File output = new File(path, filename);
BufferedWriter buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
Log.d("Success",
"Successfully wrote a file " + context.getFilesDir());
} catch (Exception e) {
e.printStackTrace();
}
Both of the following put it under /storage/emulated/0/Android/data/com.example.simplelte/files/system/stuff/test.txt
and
/storage/emulated/0/Android/data/com.example.simplelte/files/storage/emulated/0/stuff/test.txt
respectively
try {
File file = new File(context.getExternalFilesDir(Environment
.getRootDirectory().getCanonicalPath()), "stuff");
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
File output = new File(file, "test.txt");
BufferedWriter buff;
buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
buff.close();
Log.d("Success", output.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and
try {
File file = new File(context.getExternalFilesDir(Environment
.getExternalStorageDirectory().getCanonicalPath()),
"stuff");
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
File output = new File(file, "test.txt");
BufferedWriter buff;
buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
buff.close();
Log.d("Success", output.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and much more. I've followed every example I can think of. I literally just want to view the text file under Computer\Nexus 5\Internal storage\ I'm just a simple man with simple desires. Why does this have to be so complicated.
Have you tried this ?
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/");
File file = new File(dir, "text.txt");
FileOutputStream f = new FileOutputStream(file);
Related
I generated a text file and tried to save it. It doesn't work only on android Q. On android 9 , 8 and 7 it works. When I check if file exists on android 10 it works but I don't it on device . I do this :
private void createFile(Context ctx, String fileName, String text) {
File filesDir = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
filesDir = ctx.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
}
assert filesDir != null;
if (!filesDir.exists()){
if(filesDir.mkdirs()){
}
}
File file = new File(filesDir, fileName + ".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
throw new IOException("Cant able to create file");
}
}
OutputStream os = new FileOutputStream(file);
byte[] data = text.getBytes();
os.write(data);
os.flush();
os.close();
Log.e("TAG", "File Path= " + file.toString());
if(file.exists()){
Log.e("d","d");
}
File fileTemp = new File(file.getPath());
FileInputStream notes_xml = new FileInputStream(fileTemp);
byte fileContent[] = new byte[(int)notes_xml.available()];
//The information will be content on the buffer.
notes_xml.read(fileContent);
String strContent = new String(fileContent);
Log.e("content",strContent);
notes_xml.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Hey I would like to save datas and then I would like to read them and put them in a EditText
speichern.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
save();
tv.setText("gespeichert");
}
});
private void save() {
try {
File myFile = new File("bla.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(string.toString() + "\n");
myOutWriter.append(string2.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Gespeichert",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void read() {
int bla;
StringBuffer strInhalt = new StringBuffer("");
try {
FileInputStream in = openFileInput("bla.txt");
while( (bla = in.read()) != -1)
strInhalt.append((char)bla);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
What can i change?`
pelase help me
I'm usin eclipse
And i would like to safe the .txt not external.
I don't believe you are creating your file correctly:
File file = new File("test.txt");
file.createNewFile();
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write("Hello World");
fo.close();
System.out.println("file created: "+file);
url = upload.upload(file);
}
And to read this file:
try {
// open the file for reading
InputStream instream = openFileInput("test.txt");
// if file the available for reading
if (instream) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine())) {
// do something with the settings from the file
}
}
// close the file again
instream.close();
} catch (java.io.FileNotFoundException e) {
// do something if the myfilename.txt does not exits
}
And don't forget to encapsulate code with a try-catch block to catch an IOException which is thrown from these objects.
EDIT
Add this to your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
or...
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
Hope that helps! :)
I am developing an application that takes an XML file and an attachment to be sent to the following path. This path is for a fax appliance.
I keep getting this error message:
Problem processing drop file "\co1-aux01prd01.tampa.healthe\Fax_Drop\Outbox\FaxDropSample1.xml": Illegal characters in path.
The XML file and the attachment are both being created but not processed.
public class TestSender {
public static void main(String[] args) {
String outBox = "\\\\faxaux\\Fax_Drop\\Outbox";
String filename = "FaxDrop" + ".xml";
String filepath = outBox + "\\" + filename;
Writer writer = null;
try {
BufferedImage image;
URL url = new URL("http://colsolgrp.com/phone/jpg/fax8.jpg");
image = ImageIO.read(url);
//File newImage = new File("\\\\faxaux\\Fax_Drop\\Outbox\\AttachmentFolder\\attachment.jpg");
File newImage = new File("\\\\faxaux\\Fax_Drop\\Outbox\\FaxDrop\\FaxDropImage.jpg");
newImage.mkdirs();
newImage.createNewFile();
ImageIO.write(image, "jpg",newImage);
System.out.println("File has been written");
}
catch(Exception e) {
System.out.println("Could not create file");
}
try {
File f = new File(filepath);
f.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(f);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
writer = new BufferedWriter(outputStreamWriter);
// Create XML file here
}
catch (Throwable ex) {
ex.printStackTrace();
}
finally {
try {
writer.close();
}
catch (Exception ex) {
// Do nothing.
}
}
System.out.println("Success");
Try this:
URI u = new URI(URLEncoder.encode("\\co1-aux01prd01.tampa.healthe\Fax_Drop\Outbox\FaxDropSample1.xml"));
I know of cours that here were some question about this, but I still can't find answer.
I need to write some text in external storage, but this code makes application crashed. Note that String dane is this text.
void zapis2 (String dane){
Context myContext = getApplicationContext();
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file, true);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(dane);
out.close();}catch (IOException e) {
}
}
Have you got any idea. I add permision in android manifest of course.
Try this:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/foldername");
dir.mkdirs();
File file = new File(dir, "filename.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(dane); //your string which you want to store
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Hope this helps!
Contect.getExternalFilesDir(..) is only available from API8, if you run/deploy on earler versions it will crash.
I want to write data to an output file and save it on a mobile device or on a computer harddrive. I am able to get my code below to work, but have to create the directory in one step and then create the file in another. Is there a more effective way to code having to create an non-existing directory before writing a file there?
Thanks
StringBuilder Path = new StringBuilder();
Path.append(Environment.getExternalStorageDirectory().toString());
String filename = "test.txt";
String test_text = "Date, Item, Quantity, Description,";
File file = new File(Path.toString()+"/" +"Test Folder2/");
file.mkdirs();
FileOutputStream file_os = null;
try {
File file2 = new File(Path.toString()+"/" +"Test Folder2", filename);
file_os = new FileOutputStream(file2);
OutputStreamWriter osw = new OutputStreamWriter(file_os);
try {
osw.write(test_text);
} catch (IOException e) {
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
Toast.makeText(QuizSettingsActivity.this, Path.toString(),
Toast.LENGTH_LONG).show();
};
String FILENAME = "test";
String string = "Date, Item, Quantity, Description,";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
For more detail on saving file on external storage follow the link mentioned below:.http://developer.android.com/guide/topics/data/data-storage.html