Solved

Amateur question on Java

Posted on 1998-11-13
10
194 Views
Last Modified: 2010-03-30
I know of the clases and methods to read, write ...etc.
But how do I create a file in java ? What java package and
what class should I be using ?

Thanks.
0
Comment
Question by:kkandasa
10 Comments
 
LVL 4

Expert Comment

by:evijay
ID: 1227413
You have to use java.io package.

FileOutputStream fos = new FileOutputStream("Myfile.dat");

// call methods on file output stream

fos.close();


0
 

Author Comment

by:kkandasa
ID: 1227414
This assumes that a file named myfile.dat already exists. If it
does not exist, then an IOException will be thrown. I understand
in this case, Java does not create a file if it does not exist.
How do I create the file first ?
0
 
LVL 1

Expert Comment

by:satishb
ID: 1227415

Hi,

If you just give the file name you want to create to the following snippet it will create a file by that name and write data in to that file. fileName is the name of the file you want to create.

FileWriter fw = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data,0,data.length());
bw.close();

Hope this works for your case. Let me know if you need any more details.
0
 
LVL 1

Expert Comment

by:satishb
ID: 1227416
Hi,

If you just give the file name you want to create to the following snippet it will create a file by that name and write data in to that file. fileName is the name of the file you want to create.

FileWriter fw = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data,0,data.length());
bw.close();

Hope this works for your case. Let me know if you need any more details.
satish.
0
 

Author Comment

by:kkandasa
ID: 1227417
Hello,
What package does this class belong to ?
If the file already exists, what exception is thrown ?

I need to write a utilityclass in which writing messages
to a tracefile is a method. I need to check if the file exists.
If it does then write the message. If not then create the file
and write the message.
In c,       
   fid = fopen(trace_file, "a+");

the command creates the file if it does not exist. How do I do
this in Java. I just started with Java.

Thanks

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:kkandasa
ID: 1227418
Sorry, I don't fully understand.

I need to do the following.
1) Check if a specific file exists.
1) create the file if it does not already exist.
2) Write data to the file (append to the file if it already
   exists).

Thank you.
0
 
LVL 1

Expert Comment

by:satishb
ID: 1227419


Hi,

You can create a File instance with the file name.
File file = new File(fileName);
Then you can check if it exists.

if(file.exists()) { ............append to it. Check the BufferedWriter class in java.io package. }
else {
.............write to it as i wrote in  my earlier comment. It will create a file and write to it.}

Let me know if you have any questions. Check File, BufferedWriter classes in io package for details.

Good Luck
Satish.
0
 

Author Comment

by:kkandasa
ID: 1227420
Thanks, that was exactly what I needed.
0
 
LVL 1

Accepted Solution

by:
roaknog earned 20 total points
ID: 1227421
import java.io.*;

class f1  {//This program creates a file c:\temp\test.doc and writes data to it unless another path is entered after the command line java f1.

public static void main (String args[]) {

      String filepath = "c:/temp/test.doc";//default file path

      System.out.println("\n     Enter 'java f1 drive:/filepath/name.extension' or the file\n     c:/temp/test.doc is created, writen to and appended\n     by default!  You are cool!");
      for (int i = 0; i < args.length; i++) {
      filepath = args[i];
      }

      System.out.println("\n     The file " + filepath + " was opened, written to, and appended!");
      try {
      FileOutputStream fout =  new FileOutputStream(filepath);
      PrintStream OutputToFile = new PrintStream(fout);
      OutputToFile.println("RÖÄK NOG!\nTINY BUBBLES MAKE ME FEEL FINE!\nMATH IS OUR FRIEND!");
      OutputToFile.println(7 + " * " + 3 + " = " + (7 * 3));
      OutputToFile.println(15 + " / " + 5 + " = " + (15 / 5));
      }

      catch (IOException e) {
      System.out.println("Error opening file: " + e);
      }

//append string to file
      try {
      RandomAccessFile raf =  new RandomAccessFile(filepath, "rw");//open file as both read and write
      raf.seek(raf.length());//go to end of file
      raf.writeBytes("\n(C)1998 INNIEA PUBLISHING COMPANY!\n");//write to file
      }

      catch (IOException e) {
      System.out.println("Error opening file: " + e);
      }

      }
}
0
 

Author Comment

by:kkandasa
ID: 1227422
The raf method worked for both appending to an existing file & creating a new file and writing to it.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now