Date post: | 04-Jan-2016 |
Category: |
Documents |
Upload: | hamilton-klein |
View: | 43 times |
Download: | 1 times |
File and Stream (IO)
Assistant Professor
Xiaozhong Liu
http://scholarwiki.indiana.edu/S517/S517.html
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…
Input Output
jTextFieldGUIServlet
File?Database?Internet?
Error???
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…
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…
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>");}
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
Lab – Part I
Fix your assignment 1. Add try and catch to avoid possible user input error.
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
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
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
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); }
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.*;
Scanner class
boolean hasNextLine()String nextLine()boolean hasNext()String next()boolean hasNextInt()int nextInt()boolean hasNextDouble()double nextDouble()void close()
import java.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()
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(); }}
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;
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(); }}
Write to File
new FileWriter(“abc.txt”);Write to the file from START!
new FileWriter(“abc.txt”, true);Append to the file!
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);
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/
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