Solved

Amateur question on Java

Posted on 1998-11-13
10
195 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
Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

 
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

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Java Loop 6 60
why cannot we forward request once the response is committed 2 42
couple of eclipse 5 36
javap not working 8 45
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…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

772 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