CTEC 1641 Enterprise Computing II - PowerPoint PPT Presentation

1 / 35
About This Presentation
Title:

CTEC 1641 Enterprise Computing II

Description:

Using the following helper code, build a vehicle class. Include at least the attributes: ... Write a method to turn the car on and off, and updates the OnOff boolean. ... – PowerPoint PPT presentation

Number of Views:19
Avg rating:3.0/5.0
Slides: 36
Provided by: Tech63
Category:

less

Transcript and Presenter's Notes

Title: CTEC 1641 Enterprise Computing II


1
CTEC 1641Enterprise Computing II
2
Exercise 1
  • Using the following helper code, build a vehicle
    class. Include at least the attributes
  • Speed
  • Colour
  • OnOff
  • Write a method to turn the car on and off, and
    updates the OnOff boolean.
  • Write a method called ChangeSpeed which increases
    and decreases the speed by adding/subtracting the
    attribute.
  • Add a constructor to take the attributes as
    arguments
  • Demonstrate both of these methods using your
    main() method.

3
  • public class CTEC1641_Lecture4_HelperCode
  • //Some attribues
  • String Attribute1"BooRa"
  • Double ABigOleDecimal12.4
  • public int Amethod(String SomethingToSay)
  • System.out.println("I am saying something "
    SomethingToSay)
  • int TheReturnVar3
  • return TheReturnVar //Let's return a
    value
  • public static void main( String args )
  • System.out.println( "Hello, Cruel World!" )
  • //Create the object
  • CTEC1641_Lecture4_HelperCode SomeOldObject
    new CTEC1641_Lecture4_HelperCode()

4
public class CTEC1641_Lecture4_Exercise1 //Some
attributes double Speed String
Colour boolean OnOff //Base
constructor CTEC1641_Lecture4_Exercise1()
Speed 0.0 //Speed of the car.
Initially zero Colour "red" //Tis' be
a red car OnOff false //Set the car
to off initially //Another
constructor CTEC1641_Lecture4_Exercise1(double
ASpeed, String AColour, boolean CarOn)
Speed ASpeed Colour
AColour OnOff CarOn public static
void main( String args ) //Create the
object using the base constructor CTEC1641_Lectu
re4_Exercise1 TheCar new CTEC1641_Lecture4_Exerc
ise1() //Display the attributes of the
object System.out.println("---The Object
Status---") System.out.println(TheCar.Speed)
System.out.println(TheCar.Colour) System.out.p
rintln(TheCar.OnOff) System.out.println("------
-----------------") //Create the object
using another constructor CTEC1641_Lecture4_Exer
cise1 AnotherCar new CTEC1641_Lecture4_Exercise1
(65.4,"Blue",false)
5
//Display the attributes of the
object System.out.println("---The Object
Status---") System.out.println(AnotherCar.Speed
) System.out.println(AnotherCar.Colour) Syst
em.out.println(AnotherCar.OnOff) System.out.pri
ntln("-----------------------") //Lets start
the car up TheCar.TurnCarOnOff() System.out.p
rintln("Car OnOff " TheCar.OnOff) //Chang
e the speed of the car from 0 to
55.4 TheCar.Speed TheCar.ChangeSpeed(55.4)
System.out.println("The Speed of the car is
"TheCar.Speed) //Lets change the car
again TheCar.Speed TheCar.ChangeSpeed(-4.3)
System.out.println("The Speed of the car is
"TheCar.Speed) public void
TurnCarOnOff() if (OnOff true)
//If the car is already on OnOff false
//Set the car to off else
OnOff true //Set the car to
on public double ChangeSpeed(double
SpeedChange) double NewSpeed Speed
//Initialize our working variable NewSpeed
NewSpeed SpeedChange return NewSpeed
6
I/O
  • Java implements much of its communications
    within the java.io package (import java.io.)
  • Data is read and written using the concept of
    streams.
  • Two types of streams
  • Input data from a source into a program
  • Output data to a source from the program

7
Streams - Overview
  • Basic process
  • Create an object associated with the data source
    (i.e. FileInputStream, InputReaderStream)
  • Work with the stream using various methods (i.e.
    BufferReader, BufferWriter)
  • Close down the stream to release the resource. In
    virtually all cases use the close() method
  • Sometime filters can be applied to a stream to do
    some additional processing. This is done by
    associating a filter to the stream.

8
I/O Exceptions
  • When using the java.io package , any exceptions
    generated will be of the type IOException, some
    common subclasses are
  • EOFException
  • FileNotFound
  • Ensure that at the very least you catch
    IOException using a try-catch

9
File Paths
  • Paths are platform specific
  • (i.e. c\\temp\\Boo.txt, /temp/Boo.txt)
  • Java also allows a more machine independent way
    to represent paths File.Separator
  • String AFineSepCharacter File.separator
  • The separator character can be concatenated with
    the path in order to build machine independent
    paths

10
File Input - Byte
  • If the file is a binary file, or we just want to
    read bytes (i.e. ASCII)
  • FileInputStream TheFile new FileInputStream("Th
    eGoods.dat")
  • Use the read() method to read in a byte. It will
    return -1 if the end of file has been reached

11
public class CTEC1641_Lecture4_ReadBytes
public static void main(String arguments)
try FileInputStream TheFile new
FileInputStream("TheGoods.dat")
boolean TheEndOfFile false int Counter1
0 while (!TheEndOfFile) int input
TheFile.read() System.out.print(input "
") if (input -1) TheEndOfFile
true else Counter1 Counter1
1 TheFile.close() System.out.println(
"\nBytpes read " Counter1) catch
(IOException e) System.out.println("Error "
e.toString())
12
File Output Stream - Byte
  • Often there is the need to write bytes to a file.
    This is done using FileOutputString(String).
  • CAUTION If there is a file that already exists
    with the same name. It will be overwritten and
    the contents lost.
  • How to check for existing file? Use
    FileOutputString(String,Boolean).
  • String gives the name of the file
  • If Boolean is true it will append data

13
import java.io. public class
CTEC1641_Lecture4_WriteBytes public static
void main(String arguments) int SomeData
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 int
SomeMoreData 55, 56, 34, 45, 56, 61, 71, 81,
82, 84 //Lets try to write a file try
FileOutputStream TheFile new
FileOutputStream("APileOfStuff.dat") for (int
i 0 i lt SomeData.length i)
TheFile.write(SomeDatai)
TheFile.close() catch (IOException e)
System.out.println("Error "
e.toString()) //Nows lets write a file,
but check fist try FileOutputStream
TheFile new FileOutputStream("APileOfStuff.dat",
true) for (int i 0 i lt SomeMoreData.length
i) TheFile.write(SomeMoreDatai)
TheFile.close() catch (IOException e)
System.out.println("Error "
e.toString())
14
Buffered Input Streams
  • Buffered input streams allow you to store data
    that has not been handled yet. When a program
    needs the data, it goes to the buffer first. This
    can be more efficient due to the time delay of
    reading in information from external devices.
    (i.e. CD-ROM require time to spin-up) Often it
    is more efficient to read a block of information
    first then process it.

15
Buffered Input Streams
  • Buffered input streams are initialized using the
    following code
  • BufferedInputStream(InputStream) Creates a
    buffered input steam for the specified InputSteam
    object.
  • BufferedInputStream(InputStream, int)- Creates
    the specified InputStream with a buffer of int
    size
  • Use the read() method which returns an integer
    value of 0 to 255 (byte)
  • End of stream is represented by a -1

16
Buffered Byte Input Streams cont
  • Read(byte, int, int) method is also available
    which can load the steam into an array

17
Buffered Byte Output Stream
  • A buffered output stream is created using the
    following constructors
  • BufferedOutputStream(OutputStream) Creates a
    buffered output steam for the specified
    OutputStream object
  • BufferedOutputStream(OutputStream, int) Creates
    the specified OutputStream buffered stream with
    buffere of int size

18
Buffered Byte Output Stream cont
  • The output streams write(int) method can be used
    to send a single byte to the stream and the
    write(byte, int, int) method writes bytes from
    the specified byte array.
  • NOTE Although the write method takes integers as
    input, the number cannot be over 255. If it is,
    it will be stored as the remained of the number
    divided by 256.

19
Buffer Output Byte Stream cont
  • When data is directed to a stream, it is not
    output to its destination (i.e. file) until the
    buffer is filled, or called by the flush()
    method. close() will also invoke this.

20
import java.io. public class
CTEC1641_Lecture4_WriteBuffBytes public static
void main(String arguments) int SomeData
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 int
SomeMoreData 55, 56, 34, 45, 56, 61, 71, 81,
82, 84 //Lets try to write a file try
FileOutputStream TheFile new
FileOutputStream("APileOfStuff.dat") BufferedO
utputStream buff new BufferedOutputStream(TheFil
e) for (int i 0 i lt SomeData.length i)
buff.write(SomeDatai) buff.close(
) catch (IOException e) System.out.print
ln("Error " e.toString()) //Nows
lets write a file, but check fist try
FileOutputStream TheFile new
FileOutputStream("APileOfStuff.dat",true) Buff
eredOutputStream buff new BufferedOutputStream(T
heFile) for (int i 0 i lt
SomeMoreData.length i) buff.write(SomeMor
eDatai) buff.close() catch
(IOException e) System.out.println("Error "
e.toString())
21
Data Streams
  • Often we need to work with data that is not bytes
    or characters. The following filters can be used
    allow the programmer to work directly with the
    stream, rather than managing the conversion
    themselves.
  • DataInputStream data new DataInputStream(buff)
  • Each input method returns the primitive data type
    indicated by the method name.

22
Data Streams cont
  • readBoolean(), writeBoolean(boolean)
  • readByte(), writeByte(integer)
  • readDouble(), writeDouble(double)
  • readFloat() writeFloat(float)
  • readInt(), writeInt(int)
  • readLong(), writeLong(long)
  • readShout(), writeShort(int)

23
import java.io. public class
CTEC1641_Lecture4_WriteBuffBytesFilter public
static void main(String arguments) int
SomeData 97, 98, 99, 100, 114, 114, 123, 32,
221, 10 //Lets try to write a file try
FileOutputStream TheFile new
FileOutputStream("APileOfStuff.dat") Bu
fferedOutputStream buff new BufferedOutpu
tStream(TheFile) DataOutputStream data new
DataOutputStream(buff) for (int i 0 i lt
SomeData.length i) data.writeLong(SomeDat
ai) buff.close() catch
(IOException e) System.out.println("Error "
e.toString())
24
File Input Character Streams
  • Character streams work with both ASCII text and
    also Unicode
  • Use Reader and Writer to read and write files
    respectively.
  • Assocated with file using
  • FileReader ATextFile new FileReader(blah.txt)

25
File Input Character Streams cont
  • Read method is overloaded
  • read() returns the next character as an integer
  • read(char, int, int) reads character into the
    specified array with indicated starting point and
    number of characters read
  • As with byte streams they will return a -1 if
    there is nothing read.

26
import java.io. class CTEC1641_Lecture4_FileRea
derExample public static void main(String
args) try FileReader ATextFile
new
FileReader("ExampleTextFile.txt")
int TheByte0 while (TheByte ! -1)
TheByte ATextFile.read() if (TheByte
! -1) System.out.print( (char)TheByte
) System.out.println("") catch
(IOException e) System.out.println("Error
with the file")
27
TextFile Output Character Streams
  • In order to write text files use the FileWriter
    class.
  • FileWriter letters new FileWriter("TheFileToWri
    te.txt")
  • Two overloaded FileWriter methods for writing
  • write (int) - This writes out a single character
  • write (char, int, int) Writes out a specified
    amount of characters from an array.
  • write (String, int, int) Writes a character
    from a given string

28
import java.io. public class
CTEC1641_Lecture4_WriteTextFile public
static void main(String arguments) try
FileWriter letters new FileWriter("T
heFileToWrite.txt") for (int i 65 i lt 91
i) letters.write( (char)i
) letters.close() catch (IOException e)
System.out.println("Error "
e.toString())
29
Text Files Buffered Reader/Writer
  • BufferedWriter can be used to write a buffered
    character stream.
  • BufferedWriter(Writer)
  • BufferedWriter(Writer, int)
  • The Writer argument can be any of the character
    output stream classes, such as FileWriter. The
    option second argument is an integer indicating
    the size of the buffer to use.

30
Files - Misc
  • File represents a file or folder reference.
  • Uses the following constructors
  • File(String) Creates a File object with the
    specified folder no filename is indicated for
    this refers only to a file folder.
  • File(String, String) Creates a File object with
    the specified folder path and the specified name.
  • File(File, String) Creates a File object with
    its path represented by the specified File and
    its name indicated by the specified String

31
File Objects
  • There are many methods
  • Exists() method returns a Boolean value
    indicating whether the file exists
  • For a given file object, you can use the length()
    method to return a long integer indicating the
    size of the file in bytes.
  • The renameTo(File) method renames the file to the
    name specified by the File argument. A Boolean
    value is returned, indicating whether the
    operating was successful.

32
File cont
  • The delete() or deleteOnExit() method should be
    called to delete a file or folder.
  • delete() does it right away. Returns a boolean
    indicating success or failure.
  • deleteOnExit() waits for the termination of the
    program
  • getName() and getPath() methods return strings
    containing the name and path of the file.

33
File cont
  • mkdir() method can be used to create the folder
    specified. It returns a Boolean value indicating
    success or failure.
  • delete() can also be used on folders
  • isDirectory() method returns the Boolean value
    true when the File object is a folder all its
    files and subfolders

34
File cont
  • listFiles() methods returns an array of File
    object representing the contents of the file, all
    of its files and subfolders.
  • The file methods will throw a SecurityException
    if the program doesnt have the security to
    perform the file operation.

35
Exercise
  • Using the program that you developed at the start
    of class, add a method that reads in a file
    containing values that represents changes to the
    vehicles speed. Use these values to change the
    speed of the vehicle each time a new value is
    read in. When the end of the file has been
    reached, the vehicles speed is reduced to zero.
Write a Comment
User Comments (0)
About PowerShow.com