
Untitled
By: a guest on
Jun 2nd, 2012 | syntax:
None | size: 1.91 KB | hits: 14 | expires: Never
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
public class FileIO {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String fileName;
System.out.print("Enter file name: ");
fileName = scan.nextLine();
File f1 = new File(fileName);
writeFile(f1);
printFile(f1);
squareFile(f1);
}
private static void squareFile(File f) {
try{
BufferedReader in = new BufferedReader(new FileReader(f));;
String line = "";
ArrayList<String> words = new ArrayList<String>();
ArrayList<Integer> numbers = new ArrayList<Integer>();
String[] temp;
while((line = in.readLine()) != null){
temp = line.split(" ");
words.add(temp[0]);
numbers.add(Integer.parseInt(temp[1]));
}
}catch(Exception e){
}
}
private static void printFile(File f) {
try{
BufferedReader in = new BufferedReader(new FileReader(f));;
String line = "";
while((line = in.readLine()) != null){
System.out.println(line);
}
}catch(Exception e){
}
}
private static void writeFile(File f){
Random rand = new Random();
int r;
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f)));
r = rand.nextInt(11) + 10; //gives range [10,20], inclusive;
for(int i = 0; i < r; i++){
out.println(getRandomString() + " " + (rand.nextInt(10) + 1));
}
out.close();
}catch(Exception e){
}
}
private static String getRandomString() {
String ret = "";
Random rand = new Random();
for(int i = 0; i < 3; i++){
ret += (char) (rand.nextInt(26) + 65); //gives an int in the range [65,90], which is uppercase letters in ASCII
}
return ret;
}
}