Applied Programming/Files/Java
Appearance
files.java
[edit | edit source]/**
* This program demonstrates file processing.
*
* It creates a file, adds data to the file, displays the file, appends more data
* to the file, displays the file, and then deletes the file.
*
* It will not run if the file already exists.
*
* Input:
* None
*
* Output:
* A temporary file and file contents.
*
* References:
* None
*/
import java.util.*;
/**
* Runs main program logic.
*/
class Main
{
public static void main(String[] args)
{
String FILENAME = "~file.txt";
if(fileExists(FILENAME))
{
System.out.println("File already exists.\n");
System.exit(1)
}
createFile(FILENAME);
readFile(FILENAME);
appendFile(FILENAME);
readFile(FILENAME);
deleteFile(FILENAME);
}
/**
* Creates filename and adds temperature data to the file.
*
* @param filename
*
* Catches IOException and terminates the program.
*/
private static void createFile(String filename)
{
try
{
java.io.File file = new java.io.File(filename);
java.io.BufferedWriter writer =
new java.io.BufferedWriter(new java.io.FileWriter(file));
float c;
float f;
writer.write("C\tF\n");
for(c = 0; c <= 50; c++)
{
f = c * 9 / 5 + 32;
writer.write(c + "\t" + f + "\n");
}
writer.close();
}
catch(java.io.IOException e)
{
e.printStackTrace();
System.exit(2);
}
}
/**
* Reads filename and displays each line.
*
* @param filename
*
* Catches IOException and terminates the program.
*/
private static void readFile(String filename)
{
try
{
java.io.File file = new java.io.File(filename);
java.io.BufferedReader reader =
new java.io.BufferedReader(new java.io.FileReader(file));
String line;
while(true)
{
line = reader.readLine();
if (line == null)
{
break;
}
System.out.println(line);
}
reader.close();
System.out.println("");
}
catch(java.io.IOException e)
{
e.printStackTrace();
System.exit(3);
}
}
/**
* Appends temperature data to filename.
*
* @param filename
*
* Catches IOException and terminates the program.
*/
private static void appendFile(String filename)
{
try
{
java.io.File file = new java.io.File(filename);
java.io.BufferedWriter writer =
new java.io.BufferedWriter(new java.io.FileWriter(file, true));
float c;
float f;
for(c = 51; c <= 100; c++)
{
f = c * 9 / 5 + 32;
writer.write(c + "\t" + f + "\n");
}
writer.close();
}
catch(java.io.IOException e)
{
e.printStackTrace();
System.exit(4);
}
}
/**
* Deletes filename.
*
* @param filename
*/
private static void deleteFile(String filename)
{
java.io.File file;
file = new java.io.File(filename);
file.delete();
}
/**
* Determines whether or not filename exists.
*
* @param filename
*
* @return true or false
*/
private static boolean fileExists(String filename)
{
java.io.File file;
file = new java.io.File(filename);
return file.exists();
}
}
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own Java compiler / interpreter / IDE.