Solved

Amateur question on Java

Posted on 1998-11-13
10
192 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
Comment Utility
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
Comment Utility
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
Comment Utility

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
Comment Utility
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
Comment Utility
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:kkandasa
Comment Utility
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
Comment Utility


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
Comment Utility
Thanks, that was exactly what I needed.
0
 
LVL 1

Accepted Solution

by:
roaknog earned 20 total points
Comment Utility
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
Comment Utility
The raf method worked for both appending to an existing file & creating a new file and writing to it.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

743 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

12 Experts available now in Live!

Get 1:1 Help Now