Feb 16, 2012

[Java] file I/O

// Java
// text file read (line by line)
import java.io.*;
import java.util.*;   // to use "ArrayList"

public class file_IO_4 {
 
     public static void main(String[] args) {
           
            // File Open
            File oFile = new File("./animal/livestock.txt");
           
            // Creat object for File Reader
            FileReader frd = null;
            BufferedReader brd = null;
           
            // define "ArrayList" for saving line-by-line content of file 
            ArrayList<String> lineList = new ArrayList<String>();
 
            // variables for saving line by line
            String rLine = null;
            int lineNum = 0;
            boolean hasMore = true;
           
            try {
                  frd = new FileReader(oFile);
                  brd = new BufferedReader(frd);  
                                                         
                  System.out.println();
                  while (hasMore) {
                     if((rLine = brd.readLine())!= null){
                         System.out.println(rLine);
                               
                         // Add read line to ArrayList
                         lineList.add(rLine);
                         lineNum++;
                         hasMore = true;
                      } else
                         hasMore = false;                       
            }
                 
                  frd.close();
                  brd.close();
            } catch (IOException e) {
                  e.printStackTrace();
            }           
           
            // Print size of Array List 
            System.out.println();
            System.out.println(lineList.size());
            System.out.println(lineList);
            System.out.println();
           
            // Print line by line (for loop)
            lineNum = lineList.size();
            for(int i=0; i<lineNum; i++) {
             System.out.println( i +": "+lineList.get(i));
            }           
     }
}

---------------------------------------------------------------------

// Java
// file read and write

import java.io.*;   // to use file input/output
import java.util.*;  // to use Scanner (keyboard input)

class file_IO_2
{

    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedWriter bw = null;
    BufferedReader br = null;
    
    Scanner scan = new Scanner (System.in);
    
    int menuNum;
    String input, output, filename = "sentences.txt";
    
    
    void p(Object ob) {
        System.out.print(ob);
    }
        
    
    public static void main(String[] args) throws Exception
    {
        file_IO_2  f2 = new file_IO_2();
        f2.menu();
    }
    
    
    void menu() throws Exception
    {
        p("\n");
        p("\t   1. Input sentences   \n");
        p("\t   2. Print sentences   \n");
        p("\t   3. Quit   \n");
        p("\n");
        p("\t   Select :  ");
        
        while(true) {
            if(scan.hasNextInt())  {
                menuNum = scan.nextInt();
                break;
            }  else  {
                p("Please enter number between 1 and 3   \n");
            }
            }
            
        switch(menuNum)  {
            case 1:
                input();
                break;
            case 2:
                output();
                break;
            case 3:
                break;
            default:
                p("Please enter number between 1 and 3   \n");
                menu();
        }
        
        isr.close();
        br.close();
        bw.close();
    }
    
    
    void input() throws Exception 
    {
        p("\nLet's start to input sentences   \n");
        p("If you want to stop, press \"Enter\" in an empty line   \n");
        
        bw = new BufferedWriter(new FileWriter(filename));
        br = new BufferedReader(isr);
        while(!(input = br.readLine()).equals(""))  {
            bw.write(input);
            bw.newLine();
        }
        
        p("File saved \n");
        
        bw.flush();
        menu();
    }
    
    void output() throws Exception
    {
        p("\nSentences in \"" + filename + "\" \n\n");
        br = new BufferedReader(new FileReader(filename));
        int lineCnt=0;
        while(true)  {
            lineCnt++;
            output = br.readLine();
            if (output == null) {
                break;
            }
            p(lineCnt + ". " + output + "\n");
        }
        menu();
    }
    
}
------------------------------------------------------------------------

// Java
// file read and write

// 1. input # of items
// 2. input item's name, price, location
// 3. write input data in a file "item.db"
// 4. read the file and print all items' name

import java.util.*;
import java.io.*;  // to use file input, also include "throws IOException" in main method declaration, or "throws Exception" to read file (object in the file)
import java.text.DecimalFormat;  // to use decimal format

class file_IO
{

 public static void main(String[] args) throws Exception
 {
        DecimalFormat df = new DecimalFormat ("#.##");
        
        String filename = "item.db";
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
        
        // # of items
        System.out.println("total number of items");
        Scanner ni = new Scanner (System.in);    
        while(!ni.hasNextInt())
        {
            ni.next();  // if input is not integer value, ignore it.
            System.err.println("Input should be integer value");
        }
        int n = ni.nextInt();
        
        
        // keyboard input
        for (int nn=1; nn<=n; nn=nn+1)
        {
            System.out.println("Input name of item # " +nn);
            Scanner i1n = new Scanner (System.in);    
            String n1 = i1n.next();
        
            System.out.println("Input price of item # " +nn);
            Scanner i1p = new Scanner (System.in);    
            while(!i1p.hasNextDouble()) {
                i1p.next();  // if input is not integer value, ignore it.
                System.err.println("Input should be a number");  }
            double p1 = i1p.nextDouble();
            
            System.out.println("Input location of item # " +nn);
            Scanner i1l = new Scanner (System.in);    
            String l1 = i1l.next();

            Item i1 = new Item(n1, p1, l1);
            
            out.writeObject(i1);
        }
        out.close();
        
        System.out.println();
        
        
        Item read_object;
        while( (read_object = (Item) in.readObject()) != null)
        {
            System.out.println(read_object.getName());
        }
        in.close();
        
}
}
 
 
 class Item implements Serializable 
 {
    String name, location;
    Double price;
    
    public Item (String name, double price, String location)
    {
        this.name = name;
        this.price = price;
        this.location = location;
    }
    
    String getName()
    {
        return name;
    }
    
    double getPrice()
    {
        return price;
    }
    
    String getLocation()
    {
        return location;
    }
    
}

No comments:

Post a Comment