IO流、多线程、网络、XML以及反射的基本知识

//以下代码都未进行导包
IO流:
流:IO inputStream 输入流 outputStream 输出流


从数据源(文件)-> 程序 读 输入流
从程序-> 数据源(文件) 写 输出流
流的分类:
按照方向分: 
输入流:InputStream和Reader
输出流:OutputStream和Writer
按照发送数据的基本单元分:
字节流:InputStream 和OutputStream
字符流:Reader和Writer
节点流:直接可以操作数据源或目的地
包装流:不能操作数据源或目的地,主要是辅助节点流,提高性能和效率,简化操作。
文件操作流:FileInputStream 和 FileOutputStream 
BufferedReader 和BufferedWriter
二进制文件流:DataInputStream 和DataOutputStream
对象读写流:ObjectInputStream 和ObjectOutputStream


文件字节读取流
public class FileInputStreamDemo {
public static void main(String[] args) throws IOException {
// 先创建一个File对象
File f = new File("c:/abc.txt");
FileInputStream fis = new FileInputStream(f);
// 开始读 每次1一个字节
int len = 0;
byte[] b = new byte[1024];
while((len = fis.read(b))!=-1){
// byte[] 转String
System.out.println(new String(b));
}
// 读完之后
fis.close();
}


 文件字节输出流
public class FileOutputStreamDemo {
public static void main(String[] args) throws IOException {
// 如果第二个参数为true则不会覆盖原有的内容
FileOutputStream fos = new FileOutputStream("c:/abc.txt",true);
String s = "我是小王a";
// fos.write(s.getBytes(),4,s.getBytes().length-4);
fos.write(s.getBytes());
fos.close();
}


}
  
序列化和反序列化
public class ObjectSer {
public static void main(String[] args) throws Exception {
// 序列化
Student s = new Student("张三", 28, 98);


// ObjectInputStream/ObjectOutputStream 对象流
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
"c:/student.o"));
o.writeObject(s);


o.close();
// 反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"c:/student.o"));
Student ss = (Student) ois.readObject();
System.out.println(ss);
ois.close();
}


线程:
1.新生(new )->start()
2.就绪状态 ->cpu调度
3.运行状态 -> sleep join wait 进入阻塞状态
4.死亡
sleep 睡眠(毫秒,纳秒)
join 插队强制让cpu执行当前线程,其他线程阻塞
yield 让步,暂停
wait 等等 进入阻塞状态,需要唤醒notify
如何实现线程同步:给线程上锁,synchronized
同步和异步:
上锁:方法上锁,对象上锁
线程通信:
wait 自己等 和 notify 叫醒上一个等待的线程


java创建多线程
  1.继承Thread 抽象类
  2.重写run方法
  3.创建多线程类的对象
  4.调用对象的start方法启动线程


public class ThreadDemo extends Thread {
int i;


public void run() {
for (int i = 1; i <= 1000; i++) {
System.out.println("thread" + this.i + ":" + i);
}
}


public static void main(String[] args) {
ThreadDemo t = new ThreadDemo();
// 启动线程需要调用start方法
t.i = 1;
t.start();
ThreadDemo t1 = new ThreadDemo();
// 启动线程需要调用start方法
t1.i = 2;
t1.start();
for (int i = 1; i <= 1000; i++) {
System.out.println("main:" + i);
}
}


 线程常用方法


public class ThreadLifeDemo extends Thread {
String name;


public ThreadLifeDemo(String name) {
this.name = name;
}


@Override
public void run() {
for (int i = 1; i <= 1000; i++) {
System.out.println(name + ":" + i);
}
}


public static void main(String[] args) throws Exception {
ThreadLifeDemo tld1 = new ThreadLifeDemo("例子1");
ThreadLifeDemo tld2 = new ThreadLifeDemo("例子2");
ThreadLifeDemo tld3 = new ThreadLifeDemo("例子3");
ThreadLifeDemo tld4 = new ThreadLifeDemo("例子4");

tld1.start();
tld2.start();
tld3.start();
tld4.start();
}




网络:

1.IP 
Host
TCP/IP UDP
UDP:不需要建立连接,发送大小有限制64k
不安全,效率高,容易丢包
TCP:效率低,需要建立连接,安全
InetAddress IP地址类
TCP连接方式:
Socket 套接字类 客户端的套接字
ServerSocket 服务器套接字类
客户端和服务器通过流进行数据传输
IP地址一共32位 0-255
URL:代表网址(统一资源定位符)包括:协议、域名、端口号、文件和路径。
UDP连接方式:
DatagramScoket类和DatagramPacket类


上传客户端


public class FileClient {
public static void main(String[] args) throws UnknownHostException,
IOException {
Socket s = new Socket("127.0.0.1", 8888);
// 创建一个文件输出流
FileInputStream fi = new FileInputStream("c:/aaa.jpg");
BufferedInputStream bis = new BufferedInputStream(fi);
OutputStream os = s.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
byte b[] = new byte[2048];
while (bis.read(b) != -1) {
bos.write(b);
}
bos.flush();
s.shutdownOutput();
bos.close();
bis.close();
os.close();
fi.close();
s.close();
}


文件的服务器


public class FileServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8888);
while(true){
Socket s = ss.accept();
InputStream is = s.getInputStream();
File f = new File("c:/pic");
if(!f.exists()){
f.mkdirs();
}
BufferedInputStream bis = new BufferedInputStream(is);
f = new File("c:/pic/" + s.getLocalAddress().getHostAddress().replaceAll(",", "|")+"@"+new Date().getTime() + ".jpg");
FileOutputStream fo = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fo);
byte[] b = new byte[2048];
while (bis.read(b) != -1) {
bos.write(b);
}
bos.flush();
s.shutdownInput();
}
/*
bos.close();
bis.close();
fo.close();
is.close();
s.close();
ss.close();*/
}


}

XML:

xml 可扩展标记语言
xml 说明+dtd+rootTag+sonTag+text
xml 保存数据,传输数据,做属性文件(Json替代了xml的数据处理部分)
xml dom sap jdom dom4j
解析步骤:
获取文件的document对象
获取root Element
依次往下进行解析 
dom4j使用注意:先要导入dom4j的jar包


正则表达式
.匹配所有
[]匹配范围 一个字符
{0,9}出现的次数
| 或
&& 交集
x+ 至少一次
x* 0到多次
x? 0-1次
\d 数字
\D 非数字
\w a-zA-Z0-9 
\W 非a-zA-Z0-9 
\s 空白
\S 非空白
0371-8571234
0[0-9]{2,3}\-[0-9]{7,8}
0371\-[1-9][0-9]{6}


新建一个xml的对象
 
public class NewXml {
public static void main(String[] args) throws Exception {
// 获取一个文本解析器的工厂类对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 获取一个文本解析器
DocumentBuilder db = dbf.newDocumentBuilder();
// 创建一个新的文本对象
Document d = db.newDocument();
// 创建root节点
Element root = d.createElement("animal");
// 创建一个子节点
Element cat = d.createElement("cat");
// 创件子子节点
Element name = d.createElement("name");
// 创建一个文本节点
name.appendChild(d.createTextNode("小白"));
Element color = d.createElement("color");
color.appendChild(d.createTextNode("黑色"));
Element type = d.createElement("type");
type.appendChild(d.createTextNode("波斯猫"));
cat.appendChild(name);
cat.appendChild(color);
cat.appendChild(type);
root.appendChild(cat);
d.appendChild(root);
// 【1】得到转换器工厂对象
TransformerFactory transfactory = Transform
// 【2】得到转换器对象
Transformer trans = transfactory.newTransformer();
// 【3】dom源对象
DOMSource source = new DOMSource(d);
// 【4】设置输出格式
trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
// 【5】流结果对象
StreamResult result = new StreamResult(new FileOutputStream(
"src/com/sxt/animal.xml"));
// 【6】转换成xml文件
trans.transform(source, result);
}
}


解析scores.xml对象
public class ScoresParse {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
// 获取一个文本解析器的工厂类对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 获取一个文本解析器
DocumentBuilder db = dbf.newDocumentBuilder();
// 文本解析器解析出一个文本对象
Document d = db.parse("src/com/sxt/scores.xml");
// 通过文本对象获取一个元素
Element root = d.getDocumentElement();
// 获取这个元素总的所有叫student的节点
NodeList student = root.getElementsByTagName("student");
// 循环所有节点
for(int i = 0;i<student.getLength();i++){
// 每个节点强转成元素
Element e = (Element)student.item(i);
// 获取这个元素下面的所有为id的节点
Node n = e.getElementsByTagName("ID").item(0);
Node n1 = n.getFirstChild();
String ids = n1.getNodeValue();


String name = e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
String c = e.getElementsByTagName("class").item(0).getFirstChild().getNodeValue();
String score = e.getElementsByTagName("score").item(0).getFirstChild().getNodeValue();
System.out.println(ids+" "+name+" "+c+" "+score);
}
}


}


反射:

配置文件和反射的综合例子


public class Student {
String name;
int age;
double score;


public Student(String name, int age, double score) {
super();
this.name = name;
this.age = age;
this.score = score;
}


public Student() {
}


@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score
+ "]";
}



}




配置文件和反射的综合例子
public class Test {
public static Properties getPro() throws Exception {


Properties p = new Properties();
File f = new File("student.properties");
if (f.exists()) {
p.load(new FileInputStream(f));
} else {
p.setProperty("name", "admin");
p.setProperty("age", "0");
p.setProperty("score", "0");
p.store(new FileOutputStream(f), "student information");
}
return p;
}


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生姓名:");
String name = sc.next();
System.out.println("请输入学生年龄:");
int age = sc.nextInt();
System.out.println("请输入学生成绩:");
double score = sc.nextDouble();
Properties p = Test.getPro();
// 将用户输入信息存放到p对象里面
p.setProperty("name", name);
p.setProperty("age", String.valueOf(age));
p.setProperty("score", String.valueOf(score));
// 把用户信息写入到配置文件中
p.store(new FileOutputStream("student.properties"),
"student information");
// 反射对象
Class c = Class.forName("com.test.Student");
// 通过反射的全参构造方法
Constructor cc = c.getDeclaredConstructor(String.class,int.class,double.class);
// 通过全参构造方法创建对象
Student s = (Student)cc.newInstance(p.getProperty("name"),Integer.parseInt(p.getProperty("age")),Double.parseDouble(p.getProperty("score")));
// 通过反射获取toString方法
Method m = c.getDeclaredMethod("toString", null);
// 调用方法并打印返回结果
System.out.println(m.invoke(s, null));
}


}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值