Write to a File



Write to a File

Here is a small piece of code to open an empty file and write the result onto it.

import java.io.*;

class WriteFile

{

// no components and no constructors

// main method

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

{// main

// open a file to read

File outFile = new File ("A:\\result.txt");

FileOutputStream outFileStream = new FileOutputStream(outFile);

PrintWriter outStream = new PrintWriter(outFileStream);

//write values

outStream.println(987);

outStream.println(111111L);

outStream.println(2222222F);

outStream.println(33333333D);

outStream.println("This is a string");

outStream.println('A');

outStream.println(true);

//close the file

outStream.close();

}//End Main

} // end ReadFile

Here is the compilation and execution:

Microsoft(R) Windows 98

(C)Copyright Microsoft Corp 1981-1998.

C:\>a:

A:\>path c:\jdk1.2.1\bin;

A:\>javac openfilew.java

A:\>java WriteFile

A:\>

If we open the drive A, we will see the new file named result.txt. Open it we see the following lines:

987

111111

2222222.0

3.3333333E7

This is a string

A

true

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download