File not being created programmatically - java

I have written a method for an Android application:
public void doMethod()throws IOException{
Log.d("STORAGE", Environment.getExternalStorageDirectory().toString());
File file = new File(context.getExternalFilesDir("NOTES")+"TEST.txt");
Log.d("FILE", file.createNewFile()+"");
FileOutputStream os = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write("HELLO WORLD");
bw.close();
Log.d("WRITE", "DONE");
}
In spite of executing this code (calling this method from an activity), I cannot see the file TEST.txt in my phone's file manager when I open the NOTES directory.
The directory named NOTES is being created without a problem. Where is my TEST.txt file going to?

Related

Failing to write bytes in file

I have created a file and I want to write in bytes in this file but it's not working. Where is the problem?
public void writeFileExternalStorage() {
File file = new File(getExternalFilesDir(null), "hhh.txt");
try {
if(!file.exists())
file.createNewFile();
FileOutputStream outputStream ;
outputStream = new FileOutputStream(file, true);
outputStream.write(files.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The createNewFile call will return true if it has successfully created the file. You should check the result of the call, and log an error if it is false.
According to the documentation for getExternalFilesDir (javadoc):
[it m]ay return null if shared storage is not currently available.
If that happens you will call new File(null, "hhh.txt"). That is equivalent to new File("hhh.txt") (javadoc), so the file would be created in the app's "current user directory".

Writing file to internal storage

I want to write or place my file in Android Internal storage and I am doing this -
try {
File file = new File("/data/local/measurement.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content.toString());
bw.close();
Log.d("hi", "WRITTEN");
} catch (IOException e) {
e.printStackTrace();
}
I already have measurement.txt in /data/local path but nothing is being written to it. I am using emulator and I have also given permissions like
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(context.openFileOutput("myfile", MODE_PRIVATE)));
out.write(string);
out.close();
This will put the file in /data/data/<pkg>/files, private to your app, where it belongs. You don't need any permissions for this.

IOException : When Executing Java File Code in Linux box

Here is My WriteFile
WriteFile.writeFile(str, "./test/my.html");
And writeFile() method code
public static void writeFile(String content, String fileName)
{
try
{
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
This Code Working fine With Windows but in Linux I am getting below exception
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1006)
at org.sewa.util.WriteFile.writeFile(WriteFile.java:25)
Behavior of createNewFile is the same in Windows and Linux, so most likely the path of the file you're specifing exists in Windows while it does not in Linux. In your example, test/ directory does not exist in Linux in the directory where you're executing the program. If you want to create the whole path, see File#mkdirs.

FileOutputStream write binary file to a specified folder

I'm trying to write a binary file to a specified folder, however it keeps giving me an exception.
For example, if I write the file without specifying any folder the program writes it with no problem:
public void saveFile(String name) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(name + ".bin"));
out.writeObject(this);
out.close();
}
However, when I try to specify the folder the program just doesn't write the file:
public void saveFile(String name) throws IOException {
File location = new File("/path/" + name + ".bin");
FileOutputStream fos = new FileOutputStream(location);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(this);
out.close();
fos.close();
}
I tryed several different ways but still no solution.
Does anybody know what am I doing wrong?
Check if the class which you want to write is Serializable or not.
public class Foo implements java.io.Serializable{
//...
public void write() throws IOException{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Test.bin"));
os.writeObject(this);
os.close();
}
}
Another problem:
If there is no folder named path it cannot write the object
Check your code again.
The Only reason seems for non Serialization is that u might not have implemented Serializable interface
and give your path name correctly for eg:-"C:\Users\.."
Hope it works

Writing a file to sdcard

I'm trying to write a file from an Http post reply to a file on the sdcard. Everything works fine until the byte array of data is retrieved.
I've tried setting WRITE_EXTERNAL_STORAGE permission in the manifest
and tried many different combinations of tutorials I found on the net.
All I could find was using the openFileOutput("",MODE_WORLD_READABLE) method, of the activity but how my app writes file is by using a thread. Specifically, a thread is invoked from another thread when a file has to be written,
so giving an activity object didn't work even though I tried it.
The app has come a long way and I cannot change how the app is currently written.
Please, someone help me?
CODE:
File file = new File(bgdmanip.savLocation);
FileOutputStream filecon = null;
filecon = new FileOutputStream(file);
byte[] myByte;
myByte = Base64Coder.decode(seReply);
bos.write(myByte);
filecon.write(myByte);
myvals = x * 11024;
bgdmanip.savLocation holds the whole files path. seReply is a string reply from HttpPost response. The second set of code is looped with reference to x. The file is created but remains 0 bytes.
//------------------------------WRITING DATA TO THE FILE ---------------------------------
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(v.getContext(),"Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show();
txtData.setText("");
}
catch (Exception e)
{
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
//---------------------------READING DATA FROM THE FILE PLACED IN SDCARD-------------------//
btnReadSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null)
{
aBuffer += aDataRow ;
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(v.getContext(),"Done reading SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
ALONG WITH THIS ALSO WRITE THIS PERMISSION IN Android.Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The openFileOutput() method writes data to your application's private data area (not the SD card), so that's probably not what you want. You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
Here is a sample:
// Log used as debug
File log = new File(Environment.getExternalStorageDirectory(), "Log.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write(new Date().toString());
out.write(" : \n");
} catch (Exception e) {
Log.e(TAG, "Error opening Log.", e);
}

Categories