//11. 目录和文件操作
// 获取文件信息
exists(): 如果文件存在,返回true
getCanonicalPath(): 获取全名
getName(): 文件名
getParent(): 父目录
canRead(): 如果文件可读,返回true
canWrite(): 如果文件可写,返回true
lastModified(): 文件更新时间
length(): 文件大小
isFile(): 如果是文件,返回true
ifDirectory(): 如果是目录,返回true
要调用文件的这些方法,必须
File f = new File(fileName);
// 创建文件
File f = new File("c:\\test\\mytest.txt");
f.createNewFile(); // 创建mytest.txt文件到test目录下
// 修改文件名
File f = new File("c:\\test\\mytest.txt");
f.renameTo(new File("c:\\test\\google.txt"));
把mytest.txt修改成google.txt
// 删除文件
File f = new File("c:\\test\\mytest.txt");
f.delete();
// 临时文件
File f = new File("C:\\test"); // 指定一个文件夹
// 在test文件夹中创建foo前缀,tmp后缀的临时文件
File tmp = File.createTempFile("foo", "tmp", f);
tmp.deleteOnExit(); // 在程序结束时删除该临时文件
// 更改文件属性
setReadOnly(): 设置为只读
setlastModified(): 设置最后更改时间
// 列出当前文件夹的文件列表
String[] dir = new java.io.File(".").list();
java.util.Arrays.sort(dir);
for (int i = 0; i < dir.length; i++) {
System.out.println(dir[i]);
}
// 过滤文件列表
class OnlyJava implements FilenameFilter {
public boolean accept(File dir, String s) {
if (s.endsWith(".java") || s.endsWith(".class") || s.endsWith(".jar"))
return true;
}
}
// 获取根目录
File[] rootDir = File.listRoots();
for (int i = 0; i < rootDir.length; i++) {
System.out.println(rootDir[i]);
}
// 创建新目录
new File("/home/ian/bin").mkdir(); // 如果"/home/ian"存在,则可以创建bin目录
new File("/home/ian/bin").mkdirs(); // 如果"/home/ian"不存在,会创建所有的目录
//12. 国际化和本地化
// I18N资源
ResourceBundle rb = ResourceBundle.getBundle("Menus");
String label = rb.getString("exit.label");
// ResourceBundle相当于名值对,获取Menus按钮的区域属性
Menus_cn.properties: 不同区域的属性文件
// 列出有效区域
Locale[] list = Locale.getAvailableLocales();
// 指定区域
Locale cnLocale = Locale.CHINA;
// 设置默认区域
Locale.setDefault(Locale.CHINA);
// 格式化消息
public class MessageFormatDemo {
static Object[] data = {
new java.util.Date(),
"myfile.txt",
"could nto be opened"
};
public static void main(String[] args) {
String result = MessageFormat.format("At {0,time} on {0,date}, {1} {2}.", data);
System.out.println(result);
}
}
输出: At 10:10:08 on 2009-6-18, myfile.txt could nto be opened.
// 从资源文件中读消息
Widgets.properties在com.sean.cook.chap11下
ResourceBundle rb = ResourceBundle.getBundle("com.sean.cook.chap11.Widgets");
String propt = rb.getString("filedialogs.cantopen.string");
String result = MessageFormat.format(rb.getString("filedialogs.cantopen.format"), data);
//13. 网络客户端
// 访问服务器
Socket socket = new Socket("127.0.0.1", 8080);
// todo something
socket.close();
// 查找网络地址
InetAddress.getByName(hostName).getHostAddress()); // 根据主机名得到IP地址
InetAddress.getByName(ipAddr).getHostName()); // 根据IP地址得到主机名
// 连接具体异常
UnknownHostException
NoRouteToHostException
ConnectException
// Socket读写文本数据
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String remoteTime = in.readline();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.print("send message to client \r\n");
out.flush();
// Socket读写二进制数据
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
long remoteTime = (long)(in.readUnsignedByte() << 24);
DataOutputStream out = new DataOutputStream(socket.getOutputStream(), true);
// Socket读写串行化数据
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
Object o = in.readObject();
if (o instanceof Date) // 验证对象类型
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream(), true);
// UDP数据报
private final static int PACKET_SIZE = 1024;
String host = "EV001B389673DE";
InetAddress serverAddr = InetAddress.getByName(host);
DatagramSocket socket = new DatagramSocket();
byte[] buffer = new byte[PACKET_SIZE]; // 分配数据缓冲空间
DatagramPacket packet = new DatagramPacket(buffer, PACKET_SIZE, serverAddr, 8080);
packet.setLength(PACKET_SIZE-1); // 设置数据长度
socket.send(packet);
socket.receive(packet); // 接收数据
//14. 服务器端: Socket
// 创建ServerSocket
ServerSocket serverSocket;
Socket clientSocket;
serverSocket = new ServerSocket(9999);
while ((clientSocket = serverSocket.accept()) != null) {
System.out.println("Accept from client " + s.getInetAddress());
s.close();
}
// 监听内部网
public static final short PORT = 9999;
public static final String INSIDE_HOST = "acmewidgets-inside"; // 网络接口名
public static final int BACKLOG = 10; // 待发数
serverSocket = new ServerSocket(PORT, BACKLOG, InetAddress.getByName(INSIDE_HOST));
// 返回相应对象
ServerSocket serverSocket = new ServerSocket(9999);;
Socket clientSocket;
BufferedReader in = null;
PrintWriter out = null;
while (true) {
clientSocket = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "8859_1"));
out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "8859_1"), true);
String echoLine;
while ((echoLine = in.readLine()) != null) {
System.out.println("Read " + echoLine);
out.print(echoLine + "\r\n");
}
}
以上例子返回字符串,如果返回二进制,则使用DataOutputStream;返回对象,使用ObjectOutputStream
// 处理多客户端
需要把接收数据的处理放入多线程中
public class EchoServerThreaded {
public static final int ECHOPORT = 7;
public static final int NUM_THREADS = 4;
public static void main(String[] av) {
new EchoServerThreaded(ECHOPORT, NUM_THREADS);
}
public EchoServerThreaded2(int port, int numThreads) {
ServerSocket servSock;
Socket clientSocket;
try {
servSock = new ServerSocket(ECHOPORT);
} catch(IOException e) {
throw new RuntimeException("Could not create ServerSocket " + e);
}
for (int i = 0; i < numThreads; i++) {
new Handler(servSock, i).start();
}
}
}
class Handler extends Thread {
ServerSocket servSock;
int threadNumber;
Handler(ServerSocket s, int i) {
super();
servSock = s;
threadNumber = i;
setName("Thread " + threadNumber);
}
public void run() {
while (true) {
try {
System.out.println(getName() + " waiting");
Socket clientSocket;
synchronized (servSock) {
clientSocket = servSock.accept();
}
System.out.println(getName() + " starting, IP=" + clientSocket.getInetAddress());
BufferedReader is = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
PrintStream os = new PrintStream(clientSocket.getOutputStream(), true);
String line;
while ((line = is.readLine()) != null) {
os.print(line + "\r\n");
os.flush();
}
System.out.println(getName() + " ENDED ");
clientSocket.close();
} catch (IOException ex) {
System.out.println(getName() + ": IO Error on socket " + ex);
return;
}
}
}
}
// 使用SSL和JSSE保护Web服务器
SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
ServerSocket serverSocket = ssf.createServerSocket(8080);
// Log4j
Level级别: DEBUG < INFO < WARN < ERROR < FATAL < OFF
Appender: 输出信息
ConsoleAppender: 输出控制台 System.out
// 找到网络接口
Enumeration list = NetworkInterface.getNetworkInterfaces();
while (list.hasMoreElements()) {
NetworkInterface iface = (NetworkInterface)list.nextElement();
System.out.println(iface.getDisplayName());
Enumeration addrs = iface.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress addr = (InetAddress)addrs.nextElement();
System.out.println(addr);
}
}
//15. Java Mail
// 发送Mail
protected String msgRecIp = "[email protected]";
protected String msgSubject = "babytree";
protected String msgCc = "[email protected]";
protected String msgBody = "test body";
protected Session session;
protected Message msg;
public void doSend() {
// 创建属性文件
Properties props = new Properties();
props.put("mail.smtp.host", "mailhost");
// 创建Session对象
session = Session.getDefaultInstance(props, null);
session.setDebug(true);
msg = new MimeMessage(session); // 创建邮件
msg. setFrom(new InternetAddress("[email protected]"));
InternetAddress toAddr = new InternetAddress(msgRecIp);
msg.addRecipient(Message.RecipientType.TO, toAddr);
InternetAddress ccAddr = new InternetAddress(msgCc);
msg.addRecipient(Message.RecipientType.CC, ccAddr);
msg.setSubject(msgSubject);
msg.setText(msgBody);
Transport.send(msg);
}
// 发送MIME邮件
Multipart mp = new MimeMultipart();
BodyPart textPart = new MimeBodyPart();
textPart.setText(message_body); // 设置类型"text/plain"
BodyPart pixPart = new MimeBodyPart();
pixPart.setContent(html_data, "text/html");
mp.addBodyPart(textPart);
mp.addBodyPart(pixPart);
mesg.setContent(mp);
Transport.send(mesg);
// 读Mail
Store store = session.getStore(protocol);
store.connect(host, user, password);
Folder rf;
rf = store.getFolder(root);
rf = store.getDefaultFolder();
rf.open(Folder.READ_WRITE);
//16. 数据库访问
// JDO
Properties p = new Properties();
p.load(new FileInputStream("jdo.properties"));
PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(p);
PersistenceManager pm = pmf.getPersistenceManager();
// 提交数据
pm.currentTransaction().begin();
if (o instanceof Collection) {
pm.makePersistentAll((Collection) o);
} else {
pm.makePersistent(o);
}
pm.currentTransaction().commit();
pm.close();
// 取出数据
Object[] data = new Object[3];
pm.retrieveAll(data);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
pm.close();
// 数据操作
Class clz = Class.forName("oracle.jdbc.driver.OracleDriver");
String dbUrl = "jdbc:oracle:thin:@192.168.0.23:1521#:nms";
Connection conn = DriverManager.getConnection(dbUrl, "su", "1234");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from pmtable");
while (rs.next()) {
String name = rs.getString(1);
String otherName = rs.getString("name");
}
// 使用PreparedStatement提高性能,除了查询,都使用executeUpdate执行操作
PreparedStatement pstmt = conn.prepareStatement("select * from pmtable where name = ?");
pstmt.setString(1, "sean");
ResultSet rs = pstmt.executeQuery();
// 调用存储过程
CallableStatement cs = conn.prepareCall("{ call ListDefunctUsers }");
ResultSet rs = cs.executeQuery();
// 显示数据库表信息
DatabaseMetaData meta = conn.getMetaData();
meta.getDatabaseProductName();
meta.getDatabaseProductVersion();
meta.getDefaultTransactionIsolation();
/*
17. XML
SAX: 在读取文档提取相应的标记事件(元素起始、元素结束、文档起始)
DOM: 在内存中构造与文档中元素相应的树,可以遍历、搜索、修改
DTD: 验证文档是否正确
JAXP: 用于XML处理的Java API
Castor: 开源项目,用于Java对象与XML映射
*/
// 从对象中生成XML
private final static String FILENAME = "serial.xml";
public static void main(String[] args) throws IOException {
String a = "hard work and best callback";
new SerialDemoXML().write(a);
new SerialDemoXML().dump();
}
public void write(Object obj) throws IOException {
XMLEncoder os = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(FILENAME)));
os.writeObject(obj);
os.close();
}
public void dump() throws IOException {
XMLDecoder out = new XMLDecoder(new BufferedInputStream(new FileInputStream(FILENAME)));
System.out.println(out.readObject());
out.close();
}
serial.xml格式内容如下:
控制台输出
hard work and best callback
// XSLT转换XML
XSLT可以用来对输出格式进行各种控制
Transformer tx = TransformerFactory.newInstance().newTransformer(new StreamSource("people.xml"));
tx.transform(new StreamSource("people.xml"), new StreamResult("people.html"));
// 用SAX解析XML - 主要用于查找关键元素,不用全文遍历
public SaxLister() throws SAXException, IOException {
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
parser.setContentHandler(new PeopleHandler());
parser.parse("C:\\StudySource\\javacooksrc2\\xml\\people.xml");
}
class PeopleHandler extends DefaultHandler {
boolean parent = false;
boolean kids = false;
public void startElement(String nsURI, String localName, String rawName, Attributes attr) throws SAXException {
System.out.println("startElement: " + localName + "," + rawName);
if (rawName.equalsIgnoreCase("name"))
parent = true;
if (rawName.equalsIgnoreCase("children"))
kids = true;
}
public void characters(char[] ch, int start, int length) {
if (parent) {
System.out.println("Parent: " + new String(ch, start, length));
parent = false;
} else if (kids) {
System.out.println("Children: " + new String(ch, start, length));
kids = false;
}
}
public PeopleHandler() throws SAXException {
super();
}
}
// DOM解析XML - 遍历整个树
String uri = "file:" + new File("C:\\StudySource\\javacooksrc2\\xml\\people.xml").getAbsolutePath();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(uri);
NodeList nodes = doc.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
switch (n.getNodeType()) {
case Node.ELEMENT_NODE:
// todo
break;
case Node.TEXT_NODE:
// todo
break;
}
}
// 使用DTD或者XSD验证
定义好DTD或XSD文件
XmlDocument doc = XmlDocument.createXmlDocument(uri, true);
// 用DOM生成XML
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = fact.newDocumentBuilder();
Document doc = parser.newDocument();
Node root = doc.createElement("Poem");
doc.appendChild(root);
Node stanza = doc.createElement("Stanza");
root.appendChild(stanza);
Node line = doc.createElement("Line");
stanza.appendChild(line);
line.appendChild(doc.createTextNode("Once, upon a midnight dreary"));
line = doc.createElement("Line");
stanza.appendChild(line);
line.appendChild(doc.createTextNode("While I pondered, weak and weary"));
//18. RMI
a. 定义客户端与服务器之间的通信接口
public interface RemoteDate extends Remote {
public Date getRemoteDate() throws RemoteException;
public final static String LOOKUPNAME = "RemoteDate";
}
b. 编写RMI服务器
public class RemoteDateImpl extends UnicastRemoteObject implements RemoteDate {
public RemoteDateImpl() throws RemoteException {
super();
}
public Date getRemoteDate() throws RemoteException {
return new Date();
}
}
RemoteDateImpl im = new RemoteDateImpl();
System.out.println("DateServer starting...");
Naming.rebind(RemoteDate.LOOKUPNAME, im);
System.out.println("DateServer ready.");
c. 运行rmic生成stub
javac RemoteDateImpl.java
rmic RemoteDateImpl
d. 编写客户端
netConn = (RemoteDate)Naming.lookup(RemoteDate.LOOKUPNAME);
Date today = netConn.getRemoteDate();
System.out.println(today.toString());
e. 确保RMI注册表运行
rmiregistry
f. 启动服务器
java RemoteDateImpl
g. 运行客户端
java DateClient