BufferedWriter works on Windows but not Mac - java

So I am using this method to write to a file, it works totally fine on windows but when run on mac it creates the files but they are empty.
public static void writeLinesToTextFile(String path, String[] lines) {
File file = new File(r + path);
if (!file.exists()) {
try {
file.getParentFile().mkdirs();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(file.getPath()));
file.delete();
file.createNewFile();
for (int i = 0; i < lines.length; i++) {
//System.out.println(lines[i]);
bw.write(lines[i]);
bw.write(System.getProperty("line.separator"));
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I know the data is right because it prints correctly.
Thanks for any help, this has really been tripping me out.

Don't delete the file after creating a BufferedWriter. In Linux, every file has a unique file handle, so deleting and recreating a file with the same path creates 2 different file handles. I don't know what Windows does as I don't consider it a real OS, but from your post, it appears that it uses the same file handle.

Related

Any explanation as to why Output Stream only prints the last line of the translated variable to a new file instead of all the lines?

I am trying to convert English words from a text file to a new file that translates the words into pig Latin. Everything translates the way it should when it is simply printed to the console but the issue I am having is that only the last line from the initial file appears on the new one.
public static void newFile(String pigLatin) {
OutputStream os = null;
try {
os = new FileOutputStream(new File("/Users/amie/Documents/inputnewnew.pig.txt"));
os.write(pigLatin.getBytes(), 0, pigLatin.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
By default FileOutputStream is overriding the existing file. What you need to do is to use another constructor with append parameter
FileOutputStream(String name, boolean append)
like
os = new FileOutputStream(new File("/Users/...", true))
Take a look at the reference

Writing to an External File on Android --- File Doesn't Register, But Java Can Read

I'm trying to write to an external txt (or csv) file for Android. I can run an app, close it, and run it again, and readData() will read back to my log what I've stored. However, the dirFile (file directory) appears nowhere within my Android files (even if I connect it to a computer and search).
Something interesting, though: if I clear my log (similar to a list of print statements shown within Eclipse) and disconnect my phone from my computer, then reconnect it, the log reappears with everything I've ever written to my file (even if I later overwrote it)...yet the app isn't even running!
Here is my code. Please help me understand why I cannot find my file!
(Note: I've tried appending a "myFile.txt" extension to the directory, but it just causes an EISDIR exception.)
public void writeData(String dirName){
try
{
File root = new File(getExternalFilesDir(null), dirName);
// Writes to file
//
// The "true" argument allows the file to be appended. Without this argument (just root),
// the file will be overwritten (even though we later call append) rather than appended to.
FileWriter writer = new FileWriter(root, true);
writer.append("Append This Text\n");
writer.flush();
writer.close();
// Checks if we actually wrote to file by reading it back in (appears in Log)
//readData(dirName);
}
catch(Exception e)
{
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
}
If you're interested, here's the function I wrote to read in the data:
public void readData(String dirName){
try
{
File root = new File(getExternalFilesDir(null), dirName);
// Checks to see if we are actually writing to file by reading in the file
BufferedReader reader = new BufferedReader(new FileReader(root));
try {
String s = reader.readLine();
while (s != null) {
Log.v("2222", "2222 READ: " + s);
s = reader.readLine();
}
}
catch(Exception e) {
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
finally {
reader.close();
}
}
catch(Exception e) {
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
}
Thanks!
even if I connect it to a computer and search
if I clear my log (similar to a list of print statements shown within Eclipse) and disconnect my phone from my computer, then reconnect it, the log reappears with everything I've ever written to my file (even if I later overwrote it).
What you are seeing on your computer is what is indexed by MediaStore, and possibly a subset of those, depending upon whether your computer caches information it gets from the device in terms of "directory" contents.
To help ensure that MediaStore indexes your file promptly:
Use a FileOutputStream (optionally wrapped in an OutputStreamWriter), not a FileWriter
Call flush(), getFD().sync(), and close() on the FileOutputStream, instead of calling flush() and close() on the FileWriter (sync() will ensure the bytes are written to disk before continuing)
Use MediaScannerConnection and scanFile() to tell MediaStore to index your file
You can then use whatever sort of "reload" or "refresh" or whatever option is in your desktop OS's file manager, and your file should show up.
This blog post has more on all of this.
public void create(){
folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),"video");
boolean success = true;
if (!folder.exists()) {
success=folder.mkdirs();
}
if (success) {
readfile();
} else {
System.out.println("failed");
}
}
The above code will be used to crete the directory in th emobile at desired path
private void readfile() {
// TODO Auto-generated method stub
AssetManager assetManager = getResources().getAssets();
String[] files = null;
try {
files = assetManager.list("clipart");
} catch (Exception e) {
Log.e("read clipart ERROR", e.toString());
e.printStackTrace();
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("clipart/" + filename);
out = new FileOutputStream(folder + "/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("copy clipart ERROR", e.toString());
e.printStackTrace();
}
}}private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}}
this is my code used to write file in internal memory from the assets folder in project. This code can read all type(extension) of file from asset folder to mobile.
Don't forget to add permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and call the above function by
readfile();//this call the function to read and write the file
I hope this may help you.
Thank you.

Files deleting issue

I have this code, which must remove files from the directory and the directory itself:
private static void removeTempFiles(File dir){
if(!dir.exists())
return;
if(dir.isDirectory()){
for(File f : dir.listFiles())
removeTempFiles(f);
dir.delete();
}
else {
dir.delete();
}
}
but executing this code don't remove all the files. From time to time it removes all files with the folder or removes only a few files
UPD:
here is my creating file code:
File tempFolder = new File(tempPath);
tempFolder.mkdir();
tempFolder.mkdirs();
FileOutputStream fileOut = new FileOutputStream(tempPath+"/"+fileName);
OutputStreamWriter osw = new OutputStreamWriter(fileOut, "windows-1251");
try{
osw.write(file64);
} catch (IOException e){
e.printStackTrace();
}finally {
osw.close();
fileOut.close();
}
On Windows, it's normal that file deletion does not always succeed, because files can be locked by various services running on the system (antivirus, search indexing etc.). You need to add a retry loop around every file deletion call.

Java writing file - Access is denied

I'm trying to write a file using netbeans to a path inside the project directory so that other people on other PC's don't get error messages when running the same project (unable to find C://user...)
try {
File file = new File("producten.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, false);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < db.getNumberOfItems(); i++) {
bw.write("example1" + "\t");
bw.write("example1" + "\t");
bw.write("\r\n");
}
bw.close();
} catch (IOException e) { e.printStackTrace(); }
I'm getting the console error message:
Access is denied
When I use a absolute path directed to my desktop directory it works.
Locate netbeans exe file. Go to properties then compatibility
Scroll down to find and check run this program as administrator.
Fixed it for me.
I solved it by selecting sub folder in C drive
Example
try {
FileWriter fileWriter = new FileWriter("C:\\TestFolder\\DEBUG.txt");
fileWriter.append("Hello World! \n");
fileWriter.flush();
fileWriter.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Hope this will help who is still stuck with it.
You do not have write permission to that directory.

java how open file to write

I want to write a file but mixture of 3 bellow feature. how?
BufferedWriter , high volume data write needed
can append to exist text file
can set charset like "cp1256"
How mix all these features to open write file?
What you would do first is, Initiate your BufferedWriter :
`
String fileName = METHOD ARGUMENT, OR REGULAR STRING ("Output.txt");
BufferedWriter writer = null;
try {
File outFile = new File(fileName);
writer = new BufferedWriter(new FileWriter(OUTPUT NAME OF THE FILE YOU ARE WRITING. , true));
writer.write(WHAT YOU WANT TO WRITE TO THE FILE);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
Now to explain the code so I'm not just spoon feeding it to you.
When we declare the BufferedWriter writer = null; , we are setting it to null so that we don't write anything without setting a Try/Catch Exception Handler around it.
Once we are within our exception handled, we initiate a File called outFile. This will be the file we are outputting. The Argument we give it is the name of the file name. (A String Value such as, "Output.txt") NOTE: You MUST add the extension or else it won't work the way you are hoping it does.
Next, when we reference our BufferedWriter again, we initiate a new one in the try/catch handler, and inside we initiate a FileWriter (What will be doing the writing to the file). We give it two arguments. The name of the Output File("Output.txt"), and we also supply a true argument. What this does is makes the File Appendable! When we write true, we are saying we want the file to be appendable.
Finally, we write to the file, whatever it is you want to write.
As for the third feature, I don't think that FileWriter's will allow you to choose the Character Encoding that you want to write with, so unless you aren't using UTF-8, then you may want to use a PrintWriter
To do this, you would simply replace our `writer = new BufferedWriter(new FileWriter(OUTPUT NAME OF THE FILE YOU ARE WRITING. , true));
writer = new BufferedWriter(new PrintWriter(outputName, "UTF-8"));
I THINK this should work, if not, please let me know, I'll find a working solution.
public class WriteFile {
BufferedWriter out;
public void openFile(String file){
try {
out = new BufferedWriter(new FileWriter("data.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeInts(int[] ints){
try {
for(int i : ints) out.write(i+" ");
out.newLine();
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeFile(){
try {
if (out!=null)out.close();
} catch (IOException e) {
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
WriteFile wf = new WriteFile();
wf.openFile("test.txt");
wf.writeInts(new int[]{1,2,3,4,5});
wf.writeInts(new int[]{5,4,3,2,1});
wf.closeFile();
BufferedReader bf = new BufferedReader(new FileReader("test.txt"));
System.out.println(bf.readLine());
System.out.println(bf.readLine());
}
}
Output:
Line1: 1 2 3 4 5
Line2: 5 4 3 2 1

Categories

Resources