JavaDay5
I/O流
异常Throwable
-
Error
严重错误,无法自行解决
如电脑爆炸
-
Exception
可自行解决的异常:
1、RuntimeException【运行时期异常】
2、除了RuntimeException【编译时期异常】
常见异常有:空指针异常和索引越界异常
异常处理方式
常见异常处理方式有两种:
-
try…catch…finally(使用)
/* 注意: 1、try中的代码只要遇到异常,try中的其他代码不执行,直接进入到匹配catch的过程 2、如果没有对应的catch能够匹配,那么就说明该异常没有被处理,就由jvm默认处理了。 3、新版本的新写法,可以直接写一个catch,将多个异常类型使用|分割,缺点:多种异常的处理方案统一 4、只要是XxxException.一定是Exception子类,新版本的新写法中,异常类之间,不能存在继承关系 5、若写多个catch接收的话,异常类可以存在继承关系,但是父类必须写在后面 6、如果一个运行过程出现的问题,大概率是运行时期异常父类中一定会继承RuntimeException 而一般情况下,运行时期异常都是由于代码不够严谨导致的,可以通过提高代码逻辑严谨进行规避 也可以使用try...catch处理运行时期异常 7、如果一段代码,还没运行,就直接报错了,大概率是编译时期异常,父类直接继承自Exception 而编译时期异常必须要使用try...catch...进行处理 8、无论try中的代码是否报错,finally中的代码都会执行,以后的开发中finally中一般编写释放资源代码 9、有一种情况,finally不会执行,在执行finally之前,整个程序意外中止 */ public class ExceptionDemo { public static void main(String[] args) { int[] arr = {1,2,3,4}; try { System.out.println(arr[1]); System.exit(0); }catch (Exception e){ System.out.println("出错啦!"); }finally { System.out.println("好好学习"); } System.out.println("over"); } } //输出结果为2
-
throws(仅为了程序不报错)
在方法上抛出异常类,表示一种可能性:
public static void main(String[] args) throws Exception{}
File文件类操作
/*
创建功能
public boolean createNewFile()
public boolean mkdir()
public boolean mkdirs()
删除功能
public boolean delete()
重命名功能
public boolean renameTo(File dest)
判断功能
public boolean isDirectory()
public boolean isFile()
public boolean exists()
public boolean canRead()
public boolean canWrite()
public boolean isHidden()
基本获取功能
public String getAbsolutePath()
public String getPath()
public String getName()
public long length()
public long lastModified()
高级获取功能
public String[] list() 列出当前目录下所有文件以及文件夹的名字组成的字符串数组
public File[] listFiles() 列出当前目录下所有文件以及文件夹的对应的File对象组成的File对象数组
*/
public class FileDemo {
public static void main(String[] args) throws Exception{
File file1 = new File("xxxx/xxx/xx/x");
// public boolean createNewFile() 创建一个新的文件
System.out.println(file1.createNewFile());
// public boolean mkdir() 创建单极文件夹
System.out.println(file1.mkdir());
File file2 = new File("xxxx/xxx/xx/x/x.txt");
System.out.println(file2.mkdir());
//public boolean mkdirs() 创建多极文件夹
System.out.println(file2.mkdirs());
//public boolean delete() 删除一个文件夹或者文件
file1.delete();
file2.delete();
File file3 = new File("xxxx/xxx/xx/x/x.txt");
file3.delete(); // 无法直接删除一个非空文件夹
// public boolean renameTo(File dest) 重命名一个文件夹或者文件
File file4 = new File("xxxx/xxx/xx/x/x.txt"); // 需要先将目标封装成File对象
file1.renameTo(file4);
//public boolean isDirectory() 判断目标是否是一个文件夹
System.out.println(file.isDirectory());
// public boolean isFile() 判断目标是否是一个文件
System.out.println(file.isFile());
// public boolean exists() 判断目标是否存在
System.out.println(file.exists());
// public boolean canRead() 判断目标是否可读
System.out.println(file.canRead());
System.out.println(file.canWrite());
// public boolean isHidden() 判断目标是否被隐藏
System.out.println(file.isHidden());
// public String getAbsolutePath() 获取完整路径
System.out.println(file.getAbsolutePath());
// public String getPath() 获取相对路径
System.out.println(file.getPath()); // xxxx/xxx/xx/x/x.txt
// public String getName() 获取目标的名字
System.out.println(file.getName());
// public long length() 获取的目标中的字节数
System.out.println(file.length());
// public long lastModified() 获取目标最后一次修改的时间戳
System.out.println(DateUtil.getTime(file.lastModified()));
}
}
输入输出流
根据流向:
输入:外部数据——>Java程序
输出:Java程序——>外部数据
根据种类:
字节流:
字节输入流:InputStream
字节输出流:OutputStream[抽象类]
FileOutputStream[子类]
字符流:字符流=字节流+编码表
字符输入流
字符输出流
字节流
字节输出流OutputStream[抽象类]
FileOutputStream
/*
创建对象:FileOutputStream fos = new FileOutputStream("xxx/xxxx")
或:FileOutputStream fos = new FileOutputStream("xxx/xxxx", true)
写数据的方式:一次写一个字节
一次写一个字节数组
一次写一个字节数组的一部分
*/
public class FileOutputStreamDemo {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
//创建字节输出流对象
fos = new FileOutputStream("xxxx/xxx/xx/x");
//public void write(int b) 一次写一个字节
fos.write(97);
fos.write(98);
fos.write(99);
// public void write(byte[] b) 一次写一个字节数组
byte[] bytes = {100,101,102,103};
fos.write(bytes);
// public void write(byte[] b,int off,int len) 一次写字节数组的一部分
fos.write(bytes,2,2);
// 使用字节输出流写数据的时候,写字符串时,需要将字符串转字节数组再进行写入,因为字节输出流没有直接写字符串的方法
fos.write("shujia666".getBytes());
}catch (Exception e){
e.printStackTrace();
}finally {
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
FilterOutputStream
BufferedOutputStream[字节缓冲输出流]
加入了缓冲区,写数据更快。
/*
创建对象:BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("xxx/xxxx"));
或:BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("xxx/xxxx", true));
写数据的方式:一次写一个字节
一次写一个字节数组
一次写一个字节数组的一部分
*/
public class BufferedOutputStreamDemo {
public static void main(String[] args) throws Exception{
//BufferedOutputStream(OutputStream out) 创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
//创建字节缓冲输出流对象
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("xxxx/xxx/xx/x.txt",true));
// 一次写一个字节
bos.write(101);
// 一次写一个字节数组
byte[] bytes = {101,102,103,104};
bos.write(bytes);
// 一次写一个字节数组的一部分
bos.write(bytes,1,2);
bos.flush();
//释放资源
bos.close(); // 底层关闭之前,做了一次刷新操作,将内存缓冲区中的数据刷到了磁盘中
bos.write(102);
bos.flush();
}
}
字节输入流InputStream[抽象类]
FileInputStream
public class FileInputStreamDemo2 {
public static void main(String[] args) throws Exception{
//建立对象读取文件
FileInputStream fis = new FileInputStream("xxxx/xxx/xx/x.txt");
//一次读取一个字节
int i = 0;
while ((i=fis.read())!=-1){
System.out.print((char) i);
}
System.out.print((char)fis.read() );
//一次读取一个字节数组
byte[] bytes = new byte[7];
int length = fis.read(bytes);
String s = new String(bytes, 0, length);
System.out.print(s);
fis.close();
}
}
FilterInputStream
BufferedInputStream[字节缓冲输入流]
public class BufferedInputStreamDemo1 {
public static void main(String[] args) throws Exception{
//BufferedInputStream(InputStream in) 创建一个 BufferedInputStream并保存其参数,输入流 in ,供以后使用。
//创建字节缓冲输入流对象
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("xxxx/xxx/xx/x.txt"));
// 一次读取一个字节
int i = 0;
while ((i=bis.read())!=-1){
System.out.print((char) i);
}
// 一次读取一个字节数组
byte[] bytes = new byte[1024];
int length = 0;
while ((length = bis.read(bytes))!=-1){
String s = new String(bytes, 0, length);
System.out.print(s);
}
// 释放资源
bis.close();
}
}
字符流
字符流只能复制.txt文本文件,无法读写复制图片及视频
字符输出流Writer【抽象类】
OutputStreamWriter
/*
OutputStreamWriter构造方法:
OutputStreamWriter(OutputStream out) 创建一个使用默认字符编码的OutputStreamWriter。
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("xxx/xxx/xx"), 编码名称)
Writer字符输出流写数据的方式:
public void write(int c)
public void write(char[] cbuf)
public void write(char[] cbuf,int off,int len)
public void write(String str)
public void write(String str,int off,int len)
注意:
只要是字符流写数据,将来都需要进行flush操作
*/
public class OutputStreamWriterDemo {
public static void main(String[] args) throws Exception{
//OutputStreamWriter(OutputStream out) 使用平台默认的编码写字符数据到文本文件中
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src/shujia/day13/b1.txt"));
//OutputStreamWriter(OutputStream out, String charsetName) 指定编码创建字符输出流对象
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("xxxx/xxx/xx/x"),"GBK");
//public void write(int c) 一次写一个字符
osw.write(101);
osw.flush();
//public void write(char[] cbuf) 一次写一个字符数组
char[] chars = {'我','爱','中','国'};
osw.write(chars);
osw.flush();
// public void write(char[] cbuf,int off,int len) 一次写字符数组的一部分
osw.write(chars,2,2);
osw.flush();
//public void write(String str) 直接写一个字符串
osw.write("xxxxxxxxxxxxxxxxx");
osw.flush();
//public void write(String str,int off,int len) 写字符串的一部分
osw.write("张成阳是世界上最帅的男人!", 4,3);
osw.flush();
// 释放资源
osw.close();
}
}
子类FileWriter
public class FileWriterDemo1 {
public static void main(String[] args) throws Exception{
//创建字符输入流对象
InputStreamReader isr = new InputStreamReader(new FileInputStream("xxxxx.txt"),"GBK");
//FileReader(String fileName) 创建一个新的 FileReader ,给定要读取的文件的名称。
FileReader fr = new FileReader("xxxxx.txt");
//创建字符输出流对象
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("xxxx/xxx/xx/x"),"GBK");
FileWriter fw = new FileWriter("src/shujia/day13/斗罗大陆-第二章2.txt");
//1、一次读写一个字符
int i = 0;
while ((i=fr.read())!=-1){
fw.write(i);
fw.flush();
}
//2、一次读写一个字符数组
char[] chars = new char[1024];
int length = 0;
while ((length=fr.read(chars))!=-1){
fw.write(chars,0,length);
fw.flush();
}
//释放资源
fw.close();
fr.close();
}
}
BufferedWriter
/*
创建对象:BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("xxx/xxx/xx")));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("xxx/xxx/xx"), 编码名称));
BufferedWriter bw = new BufferedWriter(new FileWriter("xxx/xx/xx"));
写数据的方式:一次写一个字符
一次写一个字符数组
一次写一个字符数组的一部分
一次写一个字符串
一次写一个字符串的一部分
*/
public class BufferedWriterDemo1 {
public static void main(String[] args) throws Exception{
// BufferedWriter(Writer out) 创建使用默认大小的输出缓冲区的缓冲字符输出流。
// 创建字符缓冲输出流对象
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("xxxx/xxx/xx/x")));
// 简化写法
BufferedWriter bw = new BufferedWriter(new FileWriter("src/shujia/day13/b2.txt"));
bw.write("好好学习,天天向上!");
bw.write("\r\n");
bw.newLine(); // 自动根据当前所处的系统环境生成一个换行符
bw.write("好好学习,天天向上!");
bw.flush();
//创建字符缓冲输入流对象
//BufferedReader(Reader in) 创建使用默认大小的输入缓冲区的缓冲字符输入流。
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("xxxx/xxx/xx/x")));
// 简化写法
BufferedReader br = new BufferedReader(new FileReader("xxxx/xxx/xx/x.txt"));
// 一次读取一个字符
// 一次读取一个字符数组
// 一次读取一行 readLine()
//注意:readLine()方法无法读取到换行符
System.out.print(br.readLine());
System.out.print(br.readLine());
String line = null;
while ((line = br.readLine())!=null){
System.out.print(line);
System.out.println();
}
//释放资源
bw.close();
}
}
字符输入流Reader[抽象类]
InputStreamReader
/*
创建对象:InputStreamReader isr = new InputStreamReader(new FileInputStream("xxx/xxx/xx"))
InputStreamReader isr = new InputStreamReader(new FileInputStream("xxx/xxx/xx"), 编码名称)
读数据的方式:一次读一个字符
一次读一个字符数组
*/
public class InputStreamReaderDemo1 {
public static void main(String[] args) throws Exception{
// InputStreamReader(InputStream in)
InputStreamReader isr = new InputStreamReader(new FileInputStream("xxxx/xxx/xx/x.txt"));
// InputStreamReader(InputStream in, String charsetName) 指定编码读取字符数据
InputStreamReader isr = new InputStreamReader(new FileInputStream("xxxx/xxx/xx/x.txt"),"GBK");
//public int read() 一次读取一个字符
System.out.print((char) isr.read());
System.out.print((char) isr.read());
System.out.print((char) isr.read());
System.out.print((char) isr.read());
System.out.print((char) isr.read());
int i = 0;
while ((i=isr.read())!=-1){
System.out.print((char) i);
}
//public int read(char[] cbuf) 一次读取一个字符数组
char[] chars = new char[1024];
int length = 0;
while ((length=isr.read(chars))!=-1){
String s = new String(chars, 0, length);
System.out.print(s);
}
// 释放资源
isr.close();
}
}
子类FileReader
public class readtxt {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("src/HomeWork/data/arr1.txt");
ArrayList<String> arr2 = new ArrayList<>();
//一次读一个字符数组
char[] chars = new char[10];
int length=0;
while((length=fr.read(chars))!=-1){
String s = new String(chars, 0, length);
System.out.println(s);
arr2.add(s);
}
System.out.println(arr2);
fr.close();
}
}
BufferedReader
/*
创建对象:BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("xxx/xxx/xx")));
BufferedReader br = new BufferedReader(new FileReader("xxx/xxx/xx"));
读取数据的方式:一次读取一个字符
一次读取一个字符数组
一次读取一行,不包含换行符
*/
public class CopyFileDemo5 {
public static void main(String[] args) throws Exception{
//创建字符缓冲输入流
BufferedReader br = new BufferedReader(new FileReader("E:\\斗罗大陆2.txt"));
//创建字符缓冲输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("src/shujia/day13/斗罗大陆-第二章5.txt"));
// 一次读写一个字符
int i = 0;
while ((i=br.read())!=-1){
bw.write(i);
bw.flush();
}
// 一次读写一个字符数组
char[] chars = new char[1024];
int length = 0;
while ((length=br.read(chars))!=-1){
bw.write(chars,0,length);
bw.flush();
}
// 一次读写一行
String line = null;
while ((line=br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
//释放资源
bw.close();
br.close();
}
}
序列化
序列化:将程序中的数据转成网络中传输的数据
反序列化:将网络中传输的数据还原成程序中的数据
/*
对象输出流【序列化】:OutputStream
- ObjectOutputStream
对象输入流【反序列化】:InputStream
- ObjectInputStream
注意:
1、无论是对象输出流还是对象输入流,本质都是字节流的子类,都是字节流的一种
2、使用对象输出流序列化一个对象的时候,如果该对象的类没有实现Serializable的接口的话,该类的对象是不允许直接序列化
若没有实现,程序运行的时候,就会报错:NotSerializableException 未序列化异常
Serializable接口中,没有任何常量或抽象方法,该接口是一个标记接口
3、我们正常去写一个对象,然后从文件读取该对象是没有问题的,但是一旦我们修改了元素类中的内容,再读取的时候就报错了
java.io.InvalidClassException:
shujia.day14.Student; local class incompatible:
stream classdesc serialVersionUID = -1904573775713800401,
local class serialVersionUID = 3614172311621133233
因为我们一旦修改了类中的内容,serialVersionUID就会跟着改变,和原本存储的对象中的serialVersionUID不一致,就不允许还原。
解决方案:
1)重新写一遍,再读
2)将serialVersionUID写固定死,自己写出来,定义成常量,不可变;自动生成即可
4、如果将来对象中某个成员,不希望与对象一起序列化到网络中,磁盘中。可以使用一个关键字进行修饰该成员:transient
*/
public class ObjectOutputStreamDemo1 {
public static void main(String[] args) throws Exception {
write();
read();
}
public static void read() throws Exception {
//创建对象输入流的对象
//public ObjectInputStream(InputStream in)
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("xxxx/xxx/xx/x.txt"));
Object o = ois.readObject(); //Object o = new Student(1001, "zrx");
System.out.println(o);
Student s = (Student) ois.readObject();
System.out.println(s.getId() + "-" + s.getName());
//释放资源
ois.close();
}
public static void write() throws Exception {
// 使用对象输出流,将一个对象写到一个文件中存储
Student s1 = new Student(1001, "zrx");
//创建对象输出流的对象
// ObjectOutputStream(OutputStream out) 创建一个写入指定的OutputStream的ObjectOutputStream。
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("xxxx/xxx/xx/x.txt"));
oos.writeObject(s1);
oos.flush();
//释放资源
oos.close();
}
}
JDBC
/*
JDBC: 使用java语言连接数据库【任意数据库】。
使用JDBC连接mysql。
java之父开发的时候,其实并不知道将来java语言会被用作连接什么数据库,所以java之父并没有在jdk中做出具体的数据库连接实现。
java之父在jdk中提供了一些接口和抽象方法以及工具类,将来什么数据库想要使用java连接,那么这个数据库开发团队,可以实现这些接口
或继承这些类,在自己的类中实现对对应的数据库做操作。
要想在自己的项目中使用java操作mysql数据库,就需要去到mysql的官网中下载,mysql开发团队开发好的jar包,包中含有对应的实现类
这些实现类就是用于操作mysql的。
mysql今后常见的版本:mysql5.7.x mysql8.0.x
驱动包常见版本: 5.1.xx【mysql5.7.x】 8.0.xx【mysql5.7.x, mysql8.0.x】
如何在自己的java程序中使用xxx驱动包?【如何使用jdbc】
6步骤:
1、加载驱动类
2、创建数据库连接对象
3、创建数据库操作对象
4、执行sql语句
1)增删改
2)查询
5、如果第4步是查询的话,分析查询结果
6、释放与数据库的连接资源
*/
public class JDBCDemo1 {
public static void main(String[] args) {
Connection conn = null;
Statement state = null;
try {
//1、加载驱动类
// mysql驱动包5.1.xx版本中驱动类的路径:com.mysql.jdbc.Driver
// mysql驱动包8.0.xx版本中驱动类的路径:com.mysql.cj.jdbc.Driver
Class.forName("com.mysql.jdbc.Driver");
//2、创建数据库连接对象
//public static Connection getConnection(String url,String user, String password)
/*
url: 指定要连接的mysql服务地址以及数据库名
jdbc:mysql://master:3306/bigdata33?useUnicode=true&characterEncoding=utf-8
*/
String url = "jdbc:mysql://master:3306/shujiatest?useUnicode=true&characterEncoding=utf-8&useSSL=false";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
System.out.println("conn: " + conn);
//3、创建数据库操作对象
state = conn.createStatement();
//4、执行sql语句
state.executeUpdate(); // 增删改
/*
增加操作
*/
int i = state.executeUpdate("insert into student(sno,sname,sgender,sage,sclass) values('110','查镕贤','男',17,'安徽铜陵')");
System.out.println(i);
/*
删除操作
*/
state.executeUpdate("delete from students where name='张成阳'");
/*
修改操作
*/
state.executeUpdate("update students set age=24 where name='张三'");
int i = state.executeUpdate("delete from student where sname = '查镕贤'");
System.out.println(i);
// 查询操作
state.executeQuery();
ResultSet resultSet = state.executeQuery("select id,name,email,age,address from students where age>=19");
System.out.println(resultSet);
//5、如果第4步是查询的话,分析查询结果
//每调用一次next方法,光标向下移动一条,若还有数据,返回true,反之返回false
while (resultSet.next()){
//获取当前行的每一列数据
//方式1:已知列名的情况下,可以根据列名获取每一列的数据
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
int age = resultSet.getInt("age");
String address = resultSet.getString("address");
System.out.println(id+","+name+","+email+","+age+","+address);
//方式2:可以根据索引获取元素 从1开始
String id = resultSet.getString(1);
String name = resultSet.getString(2);
String email = resultSet.getString(3);
String age = resultSet.getString(4);
String address = resultSet.getString(5);
System.out.println(id+","+name+","+email+","+age+","+address);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(state!=null){
state.close();
}
if(conn!=null){
conn.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
来源链接:https://www.cnblogs.com/Roxan-bd/p/18671465
没有回复内容