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.
Related
I have been trying to write to a file in Android. It is not working and it doesn't even create a file. It always executes the catch block. Here is the part of my program.
private void write(){
try {
FileWriter fileWriter = new FileWriter("C:\\Users\\Administrator\\AndroidStudioProjects\\SunCalculator\\app\\src\\main\\res\\raw\\au_locations.txt");
Log.e("Data","path detected");
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
Log.e("Data","worked");
} catch (IOException e) {
e.printStackTrace();
Log.e("Data","not worked");
}
}
I also tried to create a File object and passing it to the FileWriter constructor. None of these worked. I am using Android Studio 2.3.3
You are trying to write a file in location C:\\Users.... which is the directory structure of Windows OS.
But Android is built upon Linux OS. To get the user writeable directory in android, you should use Environment.getExternalStorageDirectory() as below:
File file = new File(Environment.getExternalStorageDirectory(), filename);
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.
I'm trying to pull my text file which the name of the file was programmed according to the title of an article which is MACC is on the right track, let’s hope it will go all the way.txt but on pull it gives me this error :
[2016-08-29 11:59:06 - ddms] transfer error: No such file or directory
[2016-08-29 11:59:06] Failed to pull selection: No such file or directory
When I try to delete
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:206)
at com.android.ddmlib.JdwpPacket.movePacket(JdwpPacket.java:235)
at com.android.ddmlib.Debugger.sendAndConsume(Debugger.java:347)
at com.android.ddmlib.Client.forwardPacketToDebugger(Client.java:707)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:344)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
my source code
public void storeHTML(Context context, ArrayList<String> storeHTML) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "voicethenews");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, storeHTML.get(0) + ".txt");
FileWriter writer = new FileWriter(gpxfile);
//BufferedWriter bufferedWriter = new BufferedWriter(writer);
for(int i = 1; i < storeHTML.size(); i++) {
//bufferedWriter.newLine();
writer.append(System.getProperty("line.separator") + storeHTML.get(i));
}
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
I've searched high and low for the answer put still didn't manage to solve it. Thank you.
Please test this code:
Environment.getExternalStorageDirectory().getAbsolutePath()+ "/SOME_DIRECTORY"
I am generating a file using the following syntax
File file = new File("input.txt");
The problem is that it is saying that it is writing to the file but I am not able to locate where the file is created, I searched my entire workspace. The expectation was that it would be created in the same folder as my code which is executing.
Any ideas?
Rest of the code :
File file = new File("input.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
You could do a sop on the absolute path and you would get the path:
File file = new File("input.txt");
System.out.println("" + file.getAbsolutePath());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
When you create file through relative paths, Java uses System.getProperty("user.dir"). So, in your case the full path to file will be System.out.println(System.getProperty("user.dir") + "/input.txt");.
I've been trying to open a text file and and save each line as the contents of an arraylist. Once this has been completed I would like to save it back to a file. I have been running into errors for so long and have tried numerous techniques. I found that for some reason, the files themselves are not being created. It may just be a simple error I'm overlooking but if you could provide any help I will be thankful.
Here's the code:
public void addToFile(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations");
root.mkdirs();
File fileName = new File(root, "locationslatitude.txt");
File fileName2 = new File(root, "locationslongitude.txt");
String file = fileName.toString();
String file2 = fileName2.toString();
String theContent = Double.toString(currLatitude);
String theContent2 = Double.toString(currLongitude);
s = new Scanner(file);
while (s.hasNext()){
fileList.add(s.next());
}
s.close();
fileList.add(theContent);
s2 = new Scanner(file2);
while (s2.hasNext()){
fileList2.add(s2.next());
}
s2.close();
fileList2.add(theContent2);
try {//works for latitude file
FileWriter writer = new FileWriter(file);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
//save the arraylist back to its appropriate file
try {//works for longitude file
FileWriter writer = new FileWriter(file2);
for(String str2: fileList2) {
writer.write(str2);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
}
I believe I found the answer to the problem and I wanted to post it back on here so if anyone else faces the same problem this might help them.
The problem was that it wasn't creating the file. The directory was created using "root.mkdirs();". However, the files were not created and I was trying to read from non-existing files. This is what I believe caused the error. So, in order to fix this problem I altered the code to this:
try{
s = new Scanner(fileName);
while (s.hasNext()){
fileList.add(s.next());
}
s.close();
fileList.add(theContent);
}catch (FileNotFoundException ex){
ex.printStackTrace();
try{
fileName.createNewFile();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Hit IOException for file one", Toast.LENGTH_SHORT).show();
}
}
try{
s2 = new Scanner(fileName2);
while (s2.hasNext()){
fileList2.add(s2.next());
}
s2.close();
fileList2.add(theContent2);
}catch (FileNotFoundException ex){
ex.printStackTrace();
try{
fileName2.createNewFile();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Hit IOException for file two", Toast.LENGTH_SHORT).show();
}
}
This was the only piece of code I had to alter. The code which saved back to the file worked. I hope this will be of use to someone and thanks everyone for your help.
This code works in my project. You can use it to save ArrayList contents to text file. Make sure that the directory is created beforehand. Just iterate through your list and use println method to write it to txt file.
FileWriter outFile = new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations/nameoftextfile.txt");
PrintWriter out = new PrintWriter(outFile);
out.println("PRINT LINES WITH ME");
out.print("NOT NECCESSARILY A NEW LINE");
out.close(); // at the very end
Do not forget to catch IOException.
Have you added the following permission in the AndroidManifest.xml?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Check if the file directory etc exists on the device in the first place that you are using
/appName/savedlocations Good chance these do not exist. Wrong name for appName or savedLocations. Check this using some file explorer program. Tell us if it exists. Print out the full path name of
Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations
and see if it really exists. Just download an app for file viewing or I think you can connect to the device via eclipse as well. If you need more info on how to do it let us know. But you should first check the actual error message and report this back.
don't invent your own serialization format. java already has that.
ArrayList<String> files = ...; // whatever
// write the object to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(files);
out.close();
// read the object back
InputStream is = new FileInputStream("filename.ser");
ObjectInputStream ois = new ObjectInputStream(is);
ArrayList<String> newFiles = = (ArrayList)ois.readObject();
ois.close();