260 likes | 400 Views
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]; } }
E N D
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]; } } System.out.println(result); Array example
Given a double array, calculate the standard deviation of this array. Note that, you can use multiple methods. Array example
public static void main(String[] args) { } Array example
Information problem… Output Input Process jTextField GUI Servlet File? Database? Internet? Error???
// Process one million records While (hasMoreTask()) { DoSomething(); //May throw some error!!! } We need to handle this error somehow… This code? 1 2 3 4 5 6 7 8 ……………………………………………………………………………………..1,000,000 An error! Re-Do all the tasks? We can do something?
// Process one million records While (hasMoreTask()) { try { DoSomething(); //May throw some error!!! } catch { //Deal with this possible error! } } This code… 1 2 3 4 5 6 7 8 ……………………………………………………………………………………..1,000,000 An error! Catch this error, do something, and continue…
out.println("<h2>Compute result:</h2>"); try { intfirstnum = Integer.parseInt(request.getParameter("firstnum")); intsecondnum = 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>"); }
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(); }
public Object pop() { Object obj; if (size == 0) { throw new EmptyStackException(); } obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; } Throw statement
Fix your assignment 1. Add try and catch to avoid possible user input error. Lab – Part I
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 File
liu:~ liu237$ cat hello.txt Hello IUB from Xiaozhong liu:~ liu237$ hexdumphello.txt 0000000 48 65 6c 6c 6f 20 49 55 42 0a 66 72 6f 6d 20 58 0000010 69 61 6f 7a 68 6f 6e 67 0a 0000019 Textual context File – on unix server HEX context
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 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); } Streams
import java.io.*; Can you read the content? IUB is good! File new FileReader("test.txt") new BufferedReader(new FileReader("test.txt")) new Scanner(new BufferedReader(new FileReader("test.txt")))
import java.io.*; boolean hasNextLine() String nextLine() boolean hasNext() String next() boolean hasNextInt() int nextInt() boolean hasNextDouble() double nextDouble() void close() Scanner class
File class • a Java class to represent a file (or folder) on the local hard drive String filepath = "../../hello.txt“; File file = new File(filepath); Some Methods: boolean isDirectory() String getName() String getAbsolutePath() long length() File[ ] listFiles()
Scanner 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()); } } Read File catch (IOException e) { //If any IO exception, print it System.out.println(e.getMessage()); } finally { //Finally, close the file if (s != null) { s.close(); } }
A File abc.txt Open a file for “write”: FileWriter file= new FileWriter(“abc.txt”); Write to File BufferedWriter out = new BufferedWriter(file); out.write(“Hello Bloomington!\r\n"); out.close;
BufferedWriter out = null; try { BufferedWriter out = new BufferedWriter(new FileWriter(“abc.txt”)); out.write("Hello IUB!"); } Write to File catch (IOException e) { //If any IO exception, print it System.out.println(e.getMessage()); } finally { //Finally, close the file if (out != null) { out.close(); } }
new FileWriter(“abc.txt”); Write to the file from START! Write to File new FileWriter(“abc.txt”, true); Append to the file!
Read from File Write to File FileReader file = new FileReader("test.txt"); FileWriter file = new FileWriter("test.txt"); Compare BufferedReader reader = new BufferedReader(file); BufferedWriter writer = new BufferedReader(file); Scanner s = new Scanner(reader); while( s.hasNext()) { System.out.println(s.next()); } s.close(); writer.write(“Hello, I’m writing…”); writer.close();
<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> Servlet + File web.html copy to project folder/WebContent/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = "/web.html"; request.getRequestDispatcher(path).forward(request, response); } Servlet + File load the html or jsp file from hard drive