1 / 25

File and Stream (IO)

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]; } }

Télécharger la présentation

File and Stream (IO)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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

  3. Given a double array, calculate the standard deviation of this array. Note that, you can use multiple methods. Array example

  4. public static void main(String[] args) { } Array example

  5. Information problem… Output Input Process jTextField GUI Servlet File? Database? Internet? Error???

  6. // 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?

  7. // 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…

  8. 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>"); }

  9. 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(); }

  10. public Object pop() { Object obj; if (size == 0) { throw new EmptyStackException(); } obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; } Throw statement

  11. Fix your assignment 1. Add try and catch to avoid possible user input error. Lab – Part I

  12. 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

  13. 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

  14. 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

  15. 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

  16. 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")))

  17. import java.io.*; boolean hasNextLine() String nextLine() boolean hasNext() String next() boolean hasNextInt() int nextInt() boolean hasNextDouble() double nextDouble() void close() Scanner class

  18. 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()

  19. 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(); } }

  20. 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;

  21. 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(); } }

  22. new FileWriter(“abc.txt”); Write to the file from START! Write to File new FileWriter(“abc.txt”, true); Append to the file!

  23. 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();

  24. <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/

  25. 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

More Related