0

I am trying to write a simple data output file. When I execute the code I get a "No file exist" as the output and no data.txt file is created in the dir.

What am I missing? The odd thing is that it was working fine the other night, but when I loaded it up today to test it out again, this happened.

Here is the code:

import java.io.*;
import java.util.*;

public class DataStreams {

    public static void main(String[] args) throws IOException {

        try {

            DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\\data.txt"));
            for (int i = 0; i < 10; i++) {
                out.write(i);
            }
        } catch (IOException ioe) {
            System.out.println("No file exist");
        }
    }
}

The data file should be a simple display of numbers 1 through 9.

Thanks for your input.

Marco Acierno
  • 14,682
  • 8
  • 43
  • 53
TroutmasterJ
  • 43
  • 1
  • 1
  • 4
  • Well, after deleting and reentering the directory address of where I wanted to write the file to - it worked. I didn't answer my question yet in case anyone has anything to add as to why it might not have worked initially. I apologize for not troubleshooting this idea before posting question. – TroutmasterJ Apr 06 '14 at 19:09
  • try printing the exception which is being thrown by using ioe.printStackTrace() in the catch block. Then you can confirm what is the exception. – bgth Apr 06 '14 at 19:10

4 Answers4

0

Create a text file named data.txt in c: .You must have deleted the file. Creating that file manually will work

Junaid Shirwani
  • 360
  • 1
  • 6
  • 20
0

On Windows platforms, C:\ is a restricted path by default. Previously the application may have been run as administrator allowing access.

Solution: Use a different location

DataOutputStream out = 
    new DataOutputStream(new FileOutputStream("C:/temp/data.txt"));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

You should have a look at the exception itself:

System.out.println("No file exist");
System.out.println(ex.getMessage());

Perhaps you have not the necessary rights, to access C:\ with your program.

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43
0
  1. To write data into a file, you should first create it, or, check if it exists.Otherwise, an IOException will be raised.
  2. Writing in C:\ is denied by default, so in your case even if you created the file you will get an IOException with an Access denied message.

    public static void main(String[] args) throws IOException {
        File output = new File("data.txt");
        if(!output.exists()) output.createNewFile();
        try {
            DataOutputStream out = new DataOutputStream(new FileOutputStream(output));
            for (int i = 0; i < 10; i++) {
                out.write(i);
            }
        } catch (IOException ioe) {
            System.out.println("No file exist");
        }
    }
    
Naili
  • 1,564
  • 3
  • 20
  • 27