Solved

Amateur question on Java

Posted on 1998-11-13
10
198 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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
 

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Certificat to iSeries KeyStore 1 31
ejb example issues 3 89
JavaFX TableView not displaying correctly 3 162
Need Help! Getting a syntax error and don't understand why 3 55
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

751 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