Java-Java中的一些基础特性及API的使用
主要内容有:Java输入/输出编程、网络编程、管道流、文件访问、序列化、Scanner,以及注解、自动装箱拆箱
输入/输出(IO)
IO编程步骤
三步骤:
1.制定input & output
2.对input & output 进行读写
3.回收input & output 的资源(os级别开辟的资源)
source & idestination:文件 网络
流:将input output进行连接
input&output相对程序来说
字符流:文本文件(人类可识别)(Writer、Reader)
字节流:二进制文件(视频 音频 图片)(InputStream、OutputStream)
本质上的都是二进制,java默认使用utf-8作为字符的默认编码,一个utf-8字符占用两个字节
DateInputStream DateOnputStream :专门处理原始类型 readInt() readLong() writeInt() writeLong()
抽象类:InputStream OutputStream
对原始数据的读写,采用流InputStream和OutputStream,对各种基本数据类型和String类型的读写,采用流DataOutputStream和DataInputStream;对象读写采用流ObjectInputStream和ObjectOutputStream。
序列化,将内存中的对象转换为二进制的形式进行存储(java独有) ObjectOutputStream.write
PipedInputStream:线程间的通信
FileInputStream ifs=new FileInputStream("E:\\a.txt");
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader br= new BufferedReader(isr);
Scanner: 字符输入
PrintWriter:字符输出 java.util.
输入输出实例(利用PrintWriter与Scanner)
对标准输入输出重定向:
输出:默认情况是终端。
重定向:System.setIN(InputStream in);
System.setOut(PrintStream out);
PrintStream ps=new PrintStream(new File("a.txt"));
System.setOut(ps);
System.out.println("HW");HW显示在a.txt中。不显示在终端。
字符编码:在linux平台下。系统默认的编码是utf-8(国际编码 二个字节表示)
在win平台下,系统默认的编码是GB2312(同GBK)国标码iso-8859-1 latin-1 (表示西欧字符集)
字节流
阀值:对于字节流的操作:主要通过改变缓冲区大小来提高效率
线程通信:PipedInputStream/PipedOutputStream
序列化
序列化:ObjectOutputStream
反序列化:ObjectInputStream
对于要序列话的对象必须实现java.io.Serializebale
两个静态方法:
1.将1000个employee放入list中,然后序列化(List)
2.经list反序列化。然后打印出1000个。
transient:对于要序列化的对象,用它修饰属性的话不会被序列化。
RandomAccessFiles:随机访问文件 可以访问文件中的任意一个字节
文件指针:文件指针的位置就是下一次read的开始位置。 java。io
seek(long postition) 0:开始位置
end:文件的字节总数
seek(0);read();//读第一个字节内容
Java网络编程
socket:由操作系统来分配和管理
port:telnet 23
oracle:1521
port:1~1024 系统端口
1~65535 应用端口
七层模型: osi
TCP:握手, 保证通信的有效性 稳定
UDP:不保证一定能收到消息 速度上的高效 适合做视频,实时性较高的系统 对网络要求高
java里
TCP:ServerSocket 服务器端
Socket 客户端
UDP:DategramSocket 用于通信
DategramPacket 用于数据(发送和接受网络udp包)
java.net.*
ServerSocket ss=new ServerSocket(9999);
Socket socket=ss.accept(); //socket 用来与连接到服务器端的客户端进行通信
64.135.24.33
客户端
Scoket socket=new Socket(服务器的ip,服务的端口号);
InputStream=socket.getInputStream() //获取输入流,用来读取服务器的输出
OutputStrem=socket.getOutputStream();//获取输出流,用来想服务器发送数据
一些基础特性及API
Java的管道流基础
import java.io.*;
public class PipedStreamTest {
public static void main(String[] args) throws Exception {
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
pis.connect(pos);
new Sender(pos);
new Reciever(pis);
}
}
class Sender implements Runnable {
private PipedOutputStream pos;
public Sender(PipedOutputStream pos) {
this.pos = pos;
new Thread(this).start();
}
public void run() {
BufferedOutputStream bos = new BufferedOutputStream(pos);
DataOutputStream dos = new DataOutputStream(bos);
for (int i = 0; i < 100; i++) {
try {
dos.writeInt(i); //向Reciever线程发送
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Send:" + i);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
dos.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Reciever implements Runnable {
private PipedInputStream pis;
public Reciever(PipedInputStream pis) {
this.pis = pis;
new Thread(this).start();
}
public void run() {
BufferedInputStream bis = new BufferedInputStream(pis);
DataInputStream dis = new DataInputStream(bis);
for (int i = 0; i < 100; i++) {
try {
int result = dis.readInt(); //读取
System.out.println("Recived:" + result);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
dis.close();
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java中的随机文件访问
//byte的所有数字 -128 ~ 127 ,向文件中写入byte类型数据
public class RandomAccessFileTest {
public static void main(String[] args) throws Exception {
File file = new File("ch08/raf.db");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
//for(int i=-128;i<128;i++)
//for(byte i=-128;i<128;i++) //这样会死循环
for (byte i = -128; i < 127; i++) {
raf.writeByte(i);
if (i == 126) {
raf.writeByte(127);
}
System.out.println(i);
}
raf.seek(255);
int result = raf.readByte();
System.out.println(result);
System.out.println("File-Pointer Loc:" + raf.getFilePointer());
raf.close();
}
}
序列化
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerialTest {
public static void main(String args[]) {
String fileNameString = "em.ser";
Employee emplpyee = new Employee();
emplpyee.setAge(99);
emplpyee.setName("john");
emplpyee.setGender(true);
try {
emplpyee.save(fileNameString);
outEm(fileNameString);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void outEm(String fileName) throws Exception {
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();/* 反序列化 */
Employee employee = (Employee) obj;
System.out.println("From file em info:");
System.err.println("Name:" + employee.getName());
System.err.println("Age:" + employee.getAge());
System.err.println("Gender:"
+ ((employee.getGender() == true) ? "Male" : "Female"));
}
}
class Employee implements java.io.Serializable {
private String name;
private int age;
private boolean gender;
public Employee() {
super();
}
public Employee(String name, int age, boolean gender) {
super();
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean getGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public String toString() {
return this.getName() + this.getAge() + this.getGender();
}
public void save(String fileName) throws Exception {
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this);
oos.flush();
oos.close();
fos.close();
}
}
Scanner
import java.io.PrintWriter;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
System.out.println("plz input something:");
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
if (input.equals("exit")) {
System.exit(0);
}
pw.println("You just input:" + input);
pw.flush(); //刷新,对于支持缓存的流来说,要及时的进行刷新,
}
pw.close(); //关闭输出流
scanner.close(); //关闭输入流
}
}
annotation 注解
辅助程序运行 在注解中进行程序的配置
@Override :以@符号开头+注解类
主流框架产品都支持使用注解进行程序配置
xml文件配置(文本配置)
(xml,properties文件配置)
将程序的数据与程序本身分离
将程序的数据分离
使用注解的配置可验证(通过编译验证)
public String toString() {
}
注解:三种
1. Marker Annotation:标记注解
@Override
2. Single value Annotation:单值注解
@Test(input="abc")
3. Muti Value Annotation 多值注解
@Test(input="abc",output="ABC")
Retention:表示注解的生命周期
source:只在于源代码中
class:只存在于class文件中
注解
import java.util.*;
import static java.lang.System.out;
import java.lang.annotation.*;
import java.lang.reflect.*;
public class AnnotationTest {
@RententionTest(input = "ABC", output = "abc")
public static String toLowerCase(String str) {
return str.toLowerCase();
}
public static void main(String args[]) {
Class clz = AnnotationTest.class;
Method[] method = clz.getDeclaredMethods(); //得到类中的所有方法
for (int i = 0; i < method.length; i++) {
boolean hasAnnotation = method[i].isAnnotationPresent(RententionTest.class);
if (hasAnnotation) {
RententionTest test = (RententionTest) method[i].getAnnotation(RententionTest.class); //得Annotation
String input = test.input(); //拿到Annotation的值
String expectedOutput = test.output();
String realOutput = toLowerCase(input);
if (expectedOutput.equals(realOutput)) {
out.println("Test Successful");
} else {
throw new AssertionError("Test" + "failed!!!");
}
}
}
}
}
import java.lang.reflect.Method;
public class AnnotationTest2 {
@Test(input = "ABC", output = "acc")
public static String toLowerCase(String str) {
return str.toLowerCase();
}
public static void main(String[] args) {
Class clz = AnnotationTest.class;
Method[] method = clz.getDeclaredMethods();
for (int i = 0; i < method.length; i++) {
boolean hasAnnotation = method[i].isAnnotationPresent(Test.class);
if (hasAnnotation) {
Test test = (Test) method[i].getAnnotation(Test.class);
String input = test.input();
String expectedoutput = test.output();
String realOutput = toLowerCase(input);
if (expectedoutput.equals(realOutput)) {
System.out.println("Test successed!!");
} else {
throw new AssertionError("Test failed!!!");
}
}
}
}
}
import java.util.*;
import static java.lang.System.out;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RententionTest {
String input();
String output();
}
自动装箱拆箱
public class BoxingTest {
public static void main(String[] args) {
int i = 100;
Integer iInteger = i; //装箱
System.out.println(iInteger);
Integer iInteger1 = new Integer(200);
int i1 = iInteger1; //拆箱
System.out.println(i1);
Integer i3 = -128;
Integer i4 = -128; //判断是相等的
//-128 ~ 127 用双等号判断是相等的
if (i3 == i4) {
System.out.println("Equal!");
} else {
System.out.println("No Equal!");
}
}
}
枚举类型
import java.util.*;
import static java.lang.System.out;
enum Size //枚举类
{
//LARGE,MIDDLE,SMALL //加个封号,和不加封号都没错,最好加封号
LARGE(50) {
public String toString() {
return "size:large value:" + this.getValue();
}
},
MIDDLE(30) {
public String toString() {
return "Size:middle value:" + this.getValue();
}
},
SMALL(20) {
public String toString() {
return "Size:small value:" + this.getValue();
}
};
Size() {
}
Size(int value) {
this.value = value;
}
private int value;
public int getValue() {
return this.value;
}
}
public class EnumTest {
private Size size;
public EnumTest(Size size) {
this.size = size;
}
public static void main(String... args) {
EnumTest test = new EnumTest(Size.LARGE);
out.println(test);
}
public String toString() {
out.println(size.toString());
return Arrays.deepToString(size.values());
}
}
集合遍历
public class ForTest {
public static void main(String[] args) {
List list = new ArrayList();
list.add("abc");
list.add("xyz");
list.add("test");
for (Object obj : list) //遍历list
{
String string = (String) obj;
System.out.println(string);
}
String[] strings = new String[]{"core java", "sql", "xml", "hibernate"};
System.out.println("-------------------------------");
for (String str : strings) //遍历数组
{
System.err.println(str);
}
System.out.println("-------------------------------");
Set set = new HashSet(); //遍历Set
set.add("set1");
set.add("set2");
set.add("set3");
for (Object obj : set) {
String string = (String) obj;
System.out.println(string);
}
System.out.println("-------------------------------");
Map map = new HashMap(); //遍历Map
map.put(1, "map1");
map.put(2, "map2");
map.put(3, "map3");
for (Object obj : map.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey() + "=>" + entry.getValue());
}
}
}
格式化输出
import java.util.*;
public class FormatterTest {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
StringBuffer sb3 = new StringBuffer();
Formatter formatter = new Formatter(sb);
Formatter formatter2 = new Formatter(sb2);
Formatter formatter3 = new Formatter(sb3);
//formatter.format("%1$tY",new java.util.Date());
//System.out.println(sb);
formatter.format("%1$tY-%1$tm-%1$td %1$tD %1$tH:%1$tM:%1$tS "
+ "\n %1$tr \n%1$tF \n %1$tH/%1$tI:%1$tM:%1$tS.%1$tL", new Date());
System.out.println(sb);
System.out.println("-------------------------------");
formatter2.format("%1$tY-%1$tm-%1$td %1$tD %1$tH:%1$tM:%1$tS "
+ "\n %1$tr \n%1$tF \n %1$tH/%1$tI:%1$tM:%1$tS.%1$tL", System.currentTimeMillis());
System.out.println(sb2);
System.out.println("-------------------------------");
formatter3.format("%1$tY-%1$tm-%1$td %1$tD %1$tH:%1$tM:%1$tS "
+ "\n %1$tr \n%1$tF \n %1$tH/%1$tI:%1$tM:%1$tS.%1$tL", Calendar.getInstance());
System.out.println(sb3);
}
}
import java.util.*;
public class PrintfTest {
public static void main(String[] args) {
int i = 100;
String string = "test";
System.out.printf("%d,%s,%S \n", i, string, string);
System.out.printf(i + "," + string + "," + string.toUpperCase() + "\n");
System.out.println(i + "," + string + "," + string.toUpperCase());
System.out.printf("%1$d,%2$s,%2$S,%1$d \n", i, string);
//1$代表第一个参数,2$代表第二个参数
//%d %s 格式符
}
}
泛型
import java.util.*;
import static java.lang.System.out;
public class GenericTest {
public static void main(String... args) {
List<String> list = new ArrayList<String>();
list.add("string1");
list.add("string2");
list.add((new java.util.Date()).toString());
for (Object obj : list) {
//String string=(String)obj;
System.out.println(obj);
}
out.println("------------------------------");
Map<String, String> map = new HashMap<String, String>();
map.put("Hello", "java");
map.put("World", "sun");
map.put("HelloWorld", "eclipse");
for (String str : map.keySet()) {
out.println("key:" + str + "\tvalue:" + (String) map.get(str));
}
out.println("------------------------------");
for (Object obj : map.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey() + "=>" + entry.getValue());
}
out.println("------------------------------");
List<Number> list1 = new ArrayList<Number>();
list1.add(5.5f);
list1.add(100);
sum(list1);
out.println("------------------------------");
Integer[] arrayInt = new Integer[]{1, 100, 999};
String[] arayString = new String[]{"str1", "str2", "str3"};
print(arrayInt);
print(arayString);
}
public static void sum(List<? extends Number> list) {
Number result = new Float(0);
for (Number num : list) {
//out.println("result.floatValue:"+result.floatValue());
//result=new Float(result.floatValue()+num.floatValue());
//给对象赋值,用new的方式,太浪费空间
result = result.floatValue() + num.floatValue(); //自动装箱
//out.println("result:"+result.floatValue());
out.println("result:" + result.floatValue()); //自动拆箱
}
}
//add(E element)
public static <E> void print(E[] array) //E代表可以传入任意类型,<E> 表示声明E为任意类型
{
for (Object obj : array) {
out.println(obj);
}
}
}
简易聊天室
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.Scanner;
public class ChatServer {
private ServerSocket ss;
private List list;
//private Queue list; //解决并发安全:方法一
private Socket socket;
private static final int PORT = 9999;
private static final String WELCOME_MESSAGE = "@Welcom to chat room !";
public ChatServer() {
try {
list = new LinkedList();
//list=new ConcurrentLinkedQueue();
// 方法一:使用ConcurrentLinkedQueue解决并发安全
ss = new ServerSocket(PORT);
while (true) {
socket = ss.accept();
add(socket);
new Handler(socket); //new一个用户连接句柄
}
} catch (Exception e) {
e.printStackTrace();
}
}
//内部类,代表着一个用户连接
class Handler implements Runnable {
private Socket socket;
public Handler(Socket socket) {
this.socket = socket;
new Thread(this).start(); //new一个线程,并启动
}
public void run() {
InputStream in = null;
OutputStream out = null;
try {
//while(true)
//{
in = socket.getInputStream();
out = socket.getOutputStream();
Scanner scanner = new Scanner(in);
PrintWriter pw = new PrintWriter(out); //初始化输出对象
pw.println(WELCOME_MESSAGE); //输出欢迎信息
pw.flush();
while (scanner.hasNextLine()) //持续等待用户输入,获得客户的发言信息
{
String message = scanner.nextLine();
broadcast(socket.getInetAddress().getHostAddress() + " says:" + message);
//方法二:解决并发安全
//broadcast_1(socket.getInetAddress().getHostAddress()+" says:"+message);
//广播客户的发言
}
//pw.close();
socket.close();
//}
//scanner.close();
//in.close();
//out.close();
//socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//广播客户的发言(群发)
//解决并发安全问题,方法二
public void broadcast_1(String message) throws Exception {
int size = list.size();
for (int i = 0; i < size; i++) {
Socket socket = (Socket) list.get(i);
if (socket.isClosed()) //判断socket是否被关闭
{
System.out.println("Socket is closed,the list size is:" + list.size());
remove(socket); //如果socket关闭了,就从list中删除
System.out.println("after remove,the list size is:" + list.size());
break;
} else {
//System.out.println("not close,list size is:"+list.size());
OutputStream out = socket.getOutputStream();
PrintWriter pw = new PrintWriter(out);
pw.println(message); //把消息写到输出流
pw.flush();
}
}
}
//广播客户的发言(群发)(使用迭代器遍历)
public void broadcast(String message) throws Exception {
Iterator it = list.iterator();
while (it.hasNext()) {
Socket socket = (Socket) it.next();
if (socket.isClosed()) //监听
{
System.out.println("Socket is closed,the list size is:" + list.size());
remove(socket); //如果socket关闭了,就从list中删除
System.out.println("after remove,the list size is:" + list.size());
break; //解决并发安全,方法三
} else {
OutputStream out = socket.getOutputStream();
PrintWriter pw = new PrintWriter(out);
pw.println(message); //把消息写到输出流
pw.flush();
//pw.close();
//out.close();
}
}
}
//添加用户 上线
public void add(Object obj) {
list.add(obj);
}
//删除用户 下线
public void remove(Object obj) {
list.remove(obj);
}
public static void main(String[] args) throws Exception {
new ChatServer();
}
}
//服务端启动后,客户端只需在cmd中用telnet连接到服务端,即可发送聊天信息
//telnet 127.0.0.1 9999