file and stream (io)

25
File and Stream (IO) Assistant Professor Xiaozhong Liu http://scholarwiki.indiana.edu/S517/S517

Upload: hamilton-klein

Post on 04-Jan-2016

50 views

Category:

Documents


1 download

DESCRIPTION

http://scholarwiki.indiana.edu/S517/S517.html. File and Stream (IO). Assistant Professor Xiaozhong Liu. int [ ] nums = {5, 7, 0, 1, 6}; int result = 0; for (int i = 0; i < nums.length; i++) { if (i < 3) { result = result + nums[i]; } else { result = result – nums[i]; } } - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: File and Stream (IO)

File and Stream (IO)

Assistant Professor

Xiaozhong Liu

http://scholarwiki.indiana.edu/S517/S517.html

Page 2: File and Stream (IO)

int [ ] nums = {5, 7, 0, 1, 6};int result = 0;for (int i = 0; i < nums.length; i++) {

if (i < 3) {result = result + nums[i];

}else {

result = result – nums[i];}

}

System.out.println(result);

Array example

Page 3: File and Stream (IO)

Given a double array, calculate the standard deviation of this array.

Note that, you can use multiple methods.

Array example

Page 4: File and Stream (IO)

public static void main(String[] args) {

}

Array example

Page 5: File and Stream (IO)

Information problem…

Input Output

jTextFieldGUIServlet

File?Database?Internet?

Error???

Page 6: File and Stream (IO)

This code?

// Process one million records

While (hasMoreTask()) {

DoSomething(); //May throw some error!!!

}

Re-Do all the tasks? We can do something?

1 2 3 4 5 6 7 8 ……………………………………………………………………………………..1,000,000

An error!

We need to handle this error somehow…

Page 7: File and Stream (IO)

This code…

// Process one million records

While (hasMoreTask()) { try {

DoSomething(); //May throw some error!!! } catch { //Deal with this possible error! }}

1 2 3 4 5 6 7 8 ……………………………………………………………………………………..1,000,000

An error!Catch this error, do something,and continue…

Page 8: File and Stream (IO)

out.println("<h2>Compute result:</h2>");try {

int firstnum = Integer.parseInt(request.getParameter("firstnum"));int secondnum = Integer.parseInt(request.getParameter("secondname"));int sum = firstnum + secondnum;out.println(Integer.toString(sum));

} catch (NumberFormatException e) {

out.println("Sorry, input ERROR. Please input two numbers. ");e.printStackTrace();

}finally{

out.println("</body></html>");}

Page 9: File and Stream (IO)

try {int a = Integer.parseInt("123");System.out.println("We got a number: " + a);

}catch (NumberFormatException e) {

System.out.println("illegal input ");e.printStackTrace();

}catch (Exception e) {

System.out.println("Other errors. ");e.printStackTrace();

}

Page 10: File and Stream (IO)

public Object pop() { Object obj;

if (size == 0) { throw new EmptyStackException(); }

obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj;}

Throw statement

Page 11: File and Stream (IO)

Lab – Part I

Fix your assignment 1. Add try and catch to avoid possible user input error.

Page 12: File and Stream (IO)

File

Text file: ASCII characters, textual context. Lines of text. i.e., ABC.java or ABC.txt

Binary file: Any type of information, i.e., image, music, movie, files (including textual content). Could be compiled files, i.e., ABC.class

Page 13: File and Stream (IO)

File – on unix server

liu:~ liu237$ cat hello.txt Hello IUBfrom Xiaozhong

liu:~ liu237$ hexdump hello.txt 0000000 48 65 6c 6c 6f 20 49 55 42 0a 66 72 6f 6d 20 580000010 69 61 6f 7a 68 6f 6e 67 0a 0000019

Textual context

HEX context

Page 14: File and Stream (IO)

Streams

A stream is an abstraction derived from sequential input or output devices. An input stream produces a stream of characters.

Streams apply not just to files, but also to IO devices, Internet streams, and so on

Page 15: File and Stream (IO)

Streams try { FileInputStream fin = new FileInputStream("Filterfile.txt"); BufferedInputStream bis = new BufferedInputStream(fin); // Now read the buffered stream. while (bis.available() > 0) { System.out.print((char)bis.read()); } } catch (Exception e) { System.err.println("Error reading file: " + e); }

Page 16: File and Stream (IO)

File

Can you read the content?IUB is good!

new FileReader("test.txt")

new BufferedReader(new FileReader("test.txt"))

new Scanner(new BufferedReader(new FileReader("test.txt")))

import java.io.*;

Page 17: File and Stream (IO)

Scanner class

boolean hasNextLine()String nextLine()boolean hasNext()String next()boolean hasNextInt()int nextInt()boolean hasNextDouble()double nextDouble()void close()

import java.io.*;

Page 18: File and Stream (IO)

File class

• a Java class to represent a file (or folder) on the local hard driveString filepath = "../../hello.txt“;

File file = new File(filepath);

Some Methods:

boolean isDirectory()String getName()String getAbsolutePath()long length()File[ ] listFiles()

Page 19: File and Stream (IO)

Read FileScanner s = null;try { s = new Scanner(new BufferedReader(new FileReader("test.txt"))); //while the file has next token, print it while( s.hasNext()) { System.out.println(s.next()); }}catch (IOException e) { //If any IO exception, print it System.out.println(e.getMessage());}

finally { //Finally, close the file if (s != null) { s.close(); }}

Page 20: File and Stream (IO)

Write to File

A Fileabc.txt

Open a file for “write”: FileWriter file= new FileWriter(“abc.txt”);

BufferedWriter out = new BufferedWriter(file);

out.write(“Hello Bloomington!\r\n");

out.close;

Page 21: File and Stream (IO)

Write to FileBufferedWriter out = null;try { BufferedWriter out = new BufferedWriter(new FileWriter(“abc.txt”)); out.write("Hello IUB!");}

catch (IOException e) { //If any IO exception, print it System.out.println(e.getMessage());}

finally { //Finally, close the file if (out != null) { out.close(); }}

Page 22: File and Stream (IO)

Write to File

new FileWriter(“abc.txt”);Write to the file from START!

new FileWriter(“abc.txt”, true);Append to the file!

Page 23: File and Stream (IO)

Compare

Read from File Write to File

FileReader file = new FileReader("test.txt");

Scanner s = new Scanner(reader); while( s.hasNext()) { System.out.println(s.next()); }

s.close();

BufferedReader reader = new BufferedReader(file);

FileWriter file = new FileWriter("test.txt");

writer.write(“Hello, I’m writing…”);

writer.close();

BufferedWriter writer = new BufferedReader(file);

Page 24: File and Stream (IO)

Servlet + File<html><head><title>Compute test</title></head><body><h2>Please submit your information</h2><form method="post" action ="/S517-Web/addnums_load" ><table border="0"><tr><td valign="top">First number: </td> <td valign="top"><input type="text" name="firstnum" size="20"></td></tr><tr><td valign="top">Second number: </td> <td valign="top"><input type="text" name="secondname" size="20"></td></tr><tr><td valign="top"><input type="submit" value="Submit Info"></td></tr></table></form></body></html>

web.html copy to project folder/WebContent/

Page 25: File and Stream (IO)

Servlet + Fileprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String path = "/web.html";request.getRequestDispatcher(path).forward(request, response);

}

load the html or jsp file from hard drive