OOP lab 10

1.  Reading Input From Text Files
Designing and implementing Java programs that deal with:
1.      Reading Input From Text Files
a.       Create a File object and give it the name of the file.
\\ the file in the current folder
File myFile01 = new File(“Message.txt”);
\\ full path using the back slash
File myFile02 = new File(“D:\\CSC210\\Lab10\\READ.TXT”);
\\ full path using the forward slash
File myFile03 = new File(“D:/CSC210/Lab10/READ.TXT”);
\\ the current directory
File myFile04 = new File(“.”);
b.       Pass the File object to a Scanner object to read from it.
Scanner reader01 = new Scanner(myFile01);
º Steps a and b can be combined as:
Scanner reader01 = new Scanner(new File(“Message.txt”);
c.        Use the methods of the Scanner class normally, i.e., hasNextInt, nextInt, next, nextDouble, etc.
reader01.hasNextInt();
reader01.nextInt();

NOTES:
î  If the file does not exist, a FileNotFoundException is thrown.
î  ALWAYS make sure to close your files!

Note:
You can create your own “data.txt” (as shown in figure) file OR you can use the attached file below.  To use the attached file, (1) double click it (2) confirm the warning message by clicking the “Yes” button (3) store the file in your project folder by clicking “File” then “Save As…”.                                                               


SOURCE CODE:
mport java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class task1 {
  
public static void main(String[] args){
    Scanner input = null;
    try{
      System.out.println("Trying to open \"data.txt\" file...");
      input = new Scanner(new File("data.txt"));
    }
    catch(FileNotFoundException e){
      System.out.println("File data.txt was not found ");
      System.out.println("or could not be opened.");
      System.exit(0);
    }

    int next, sum = 0;
    while (input.hasNextInt()){
      next = input.nextInt();
      sum = sum + next;
    }

    input.close();
    System.out.println("Sum of the numbers is " + sum);
  }

}

OUTPUT:





SOURCE CODE:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class task2 {
   
  public static void main(String[] args){
    Scanner input = null;
    PrintWriter output = null;
   
    try{
      System.out.println("Trying to open \"orignal.txt\" file...");
      input = new Scanner(new File ("orignal.txt"));
      output = new PrintWriter(new File("number.txt"));
    }
    catch(FileNotFoundException e){
      System.out.println("Problem opening files.");
      System.exit(0);
    }

    String line = null;
    int count = 0;
    while (input.hasNextLine()){
      line = input.nextLine();
      count++;
      output.println(count + " " + line);
    }

    input.close();
    output.close();
    System.out.println("Process done successfully");
  }

}




SOURCE CODE:
public class Account {
    private String acctNum;
  private String fName;
  private double balance;
 
  public Account (String num, String name, double bal) {
    acctNum = num;
    fName = name;
    balance = bal;
  }

    public String getAcctNum() {
        return acctNum;
    }

    public void setAcctNum(String acctNum) {
        this.acctNum = acctNum;
    }

    public String getfName() {
        return fName;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

   
    public String toString() {
        return "Account Number = " + acctNum + "\nFirst Name=" + fName + "\nBalance = " + balance;
    }
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.Formatter;
public class fileoutput {
        public static void main (String [] args) {
       
        //Create an arraylist to store customers
        ArrayList<Account> customers = new ArrayList<Account> ();
       
        //create some sample customers and add to list
        Account a = new Account ("123", "Sam", 123.65);
        customers.add(a);
        a = new Account("234", "Sue", 423.35);
        customers.add(a);
        a = new Account("144", "Mark", 555.25);
        customers.add(a);
        //open a file
        Formatter output = null;
       
        //must open the file in a try catch block
        try {
            output = new Formatter("data.txt");
        } catch (IOException e) {
            System.out.println("There is an error - exiting");
            System.exit(1);
        }
       
        //write everything from list to output
        for (Account x: customers)
            output.format("%s %s %.2f\n",
                          x.getAcctNum(),
                                       x.getfName(),
                                       x.getBalance());
       
        output.close();      
    }   }
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class fileinput {
    public static void main (String [] args) {   
       
        ArrayList <Account> list = new ArrayList<Account> ();
    
        Scanner s = null;
        try {
            s = new Scanner (new File ("data.txt"));
        } catch (IOException e) {
            System.out.println("Error opening file");
            System.exit(1);
        }
       
        String aNum, fName;
        double bal;
       
        while (s.hasNext()) {
          
            Account a = new Account(s.next(),s.next(), s.nextDouble());
            list.add(a);
        }
        for(Account x: list)
            System.out.println(x) }}
OUTPUT:






SOURCE CODE:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Connecting2DB {
    public Connection setConnection(){
        String dataSourceName="database/sms.accdb";
        String dir = System.getProperty("user.dir");
        String url = "jdbc:ucanaccess://"+dir+"/" + dataSourceName;
        //String url = "jdbc:ucanaccess://C:/Users/INTEL/Documents/NetBeansProjects/prjPassword/database/PasswordDB.accdb";
        Connection con=null;
        try {
              con = DriverManager.getConnection(url);
        }
        catch(Exception sqlEx){
                    System.out.println(sqlEx);
        }
        return con;
    }
    public boolean matchPassword(String user, String pass){
        boolean successful =false;
        try {
             
            Connection con = setConnection(); 
            Statement st = con.createStatement();
            String sql = "SELECT * FROM Password where username = '"+user+"'";
            ResultSet rs = st.executeQuery(sql);
            while(rs.next()){
              String userName = rs.getString("UserName");
              String password = rs.getString("Password");
              if(user.equals(userName) && pass.equals(password))
                  successful = true;
              else
                  successful = false;
            }
            con.close();
        }
        catch(Exception sqlEx){
                    System.out.println(sqlEx);
        }    
        return successful;
    }
    public boolean searchPassword(String user, String pass){
        boolean found =false;
        try {
              Connection con = setConnection();   
              Statement st = con.createStatement();
              String sql = "SELECT * FROM Password where username ='"+user+"' and password = '"+pass+"'";
              ResultSet rs = st.executeQuery(sql);
              while(rs.next()){
                  String userName = rs.getString("UserName");
                  String password = rs.getString("Password");
                  if(pass.equals(password))
                      found = true;
                  else
                      found = false;
              }
              con.close();
              }catch(Exception sqlEx){
                    System.out.println(sqlEx);
    }    
        return found;
    }
    public void updatePassword(String user, String pass){
        try {
            Connection con = setConnection();   
            PreparedStatement ps = con.prepareStatement(
            "UPDATE Password SET password = ? WHERE username = ? ");
            ps.setString(1,pass);
            ps.setString(2,user);
            ps.executeUpdate();
            ps.close();
        }
        catch(Exception sqlEx){
           System.out.println(sqlEx);
    }    
  }
}





Comments

Popular posts from this blog

Computer Programming Lab 5

Computer Programming lab 11

Computer Programming Lab 4