java基础学习笔记之java oop高级java异常处理机制、集合、文件操作、序列化与反序列化、字符串处理(三)

JAVA异常处理机制

一、什么异常(Exception)

1.生活中异常:不正常事件(意外)
2.程序异常:异常是指在程序的运行过程中所发生的不
正常的事件(例外,错误),它会中断正在运行的程序。
3.什么是异常处理:java编程语言使用异常处理机制为程序提供了错误处理的能力(不是解决错误).
4.异常处理的作用:增强的稳定性、健壮性.
5.java异常处理的关键字
try、catch、finally、throw、throws
代码示例

package 理解异常;

import java.io.IOException;
import java.util.Scanner;

import org.apache.log4j.Logger;

public class 异常 {
	//创建记录器对象
	static Logger logger=Logger.getLogger(异常.class);
	
	public static void main(String[] args) {
	   Scanner input=new Scanner(System.in); 
	   int res=0;
	  try{
	       System.out.println("请输入被除数:");
	       int i =input.nextInt();
	       System.out.println("请输入除数:");
	       int j =input.nextInt();     
	       //计算
	       res=i/j;   
	      
	      //一个错误对应一个类类型  
	  }catch(Exception e){
		   //注意:exception是异常的根类
		  //获取错误信息
		//  System.out.println(e.getMessage());  
		  //输出错误信息
		 // e.printStackTrace();
		  //采用login 4j记录错误
		  //记录
		  logger.error("输入不区配:"+e.getMessage());
	   }
       //输出
       System.out.println("结果是:"+res);
       System.out.println("程序继承往下执行:");
       int s=input.nextInt();
	}

}

注意:使用log4j时候,需要导入log4j的jar以及将配置文件放在项目根目录下
log4j.properties配置内容如下

###log 4j\u914  ###
log4j.rootLogger=debug, stdout,logfile

### stdout 配置控制台记录日志的方式   ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout

### logfile 配置文记录日志的方式 jbit.log ###
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}%l %F %p %m%n


二、异常处理语句:

try{
试图执行的代码块
}catch(异常类型){
出错时执行代码块
}finally{
有错没错都执行
}
注意:finally块可有可无
代码示例

import java.util.InputMismatchException;
import java.util.Scanner;

public class trycatchfinally {
	public static void main(String[] args) {
	   Scanner input=new Scanner(System.in); 
	   int res=0;
	  try{
	       System.out.println("请输入被除数:");
	       int i =input.nextInt();
	       System.out.println("请输入除数:");
	       int j =input.nextInt();     
	       //计算
	       res=i/j; 
	       }
       catch(InputMismatchException e){  //输入不匹配 
		  System.out.println("出错啦:"+e.getMessage());  
	   }
	   catch(ArithmeticException e){  //除数为0
			  System.out.println("出错啦:"+e.getMessage());  
	   }catch(Exception e){  //除数为0
			  System.out.println("出错啦:"+e.getMessage());  
	   }
	
	  
	  finally{
		  System.out.println("有错没错我都执行....");
	  }
       //输出
       System.out.println("结果是:"+res);
       System.out.println("程序继承往下执行:");
       int s=input.nextInt();
	}

}

三、常见异常类型

exception是异常根类
常用异常子类有:
ArithmeticException 零作为除数
ArrayIndexOutOfBoundsException 数组下标越界
NullPointerException 尝试访问 null 对象成员
IllegalArgumentException 方法接收到非法参数
ClassCastException 对象强制类型转换出错

四、获取异常的错误信息

1.获取错误信息
System.out.println(e.getMessage());
2.输出异常堆栈信息
e.printStackTrace();

五、多重catch

  try{}
   catch(异常子类型 e){}
   catch(异常子类型 e){}
   catch(Exception e) {  }

六、throws关键字的作用

1.使用throws声明方法异常,将异常交给调用者处理.
public class 类名{
//声明方法异常
public void methodName() throws 异常类型1,异常类型2{
}
}
代码示例

import java.util.InputMismatchException;
import java.util.Scanner;

//数学类
public class Math {
	  //求商   声明方法异常
	public void getRes() throws InputMismatchException,ArithmeticException,Exception{
		   int res=0;
		   Scanner input=new Scanner(System.in);
		   System.out.println("请输入被除数:");
	       int i =input.nextInt();
	       System.out.println("请输入除数:");
	       int j =input.nextInt();     
	       //计算
	       res=i/j; 
	       System.out.println("结果是:"+res);
	}
}
import java.util.InputMismatchException;

public class TestMath {
     /**
	 * @param args
	 * @throws Exception 
	 * @throws ArithmeticException 
	 * @throws InputMismatchException 
	 */
	public static void main(String[] args) {
      Math math=new Math();
  
       try {
		math.getRes();
		} catch (InputMismatchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ArithmeticException e) {
		  e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  //强制异常处理
	 
	
   
	
	
	}

}

七、throw关键字抛出异常

作用:抛出异常对象
throw new 异常类();
代码示例

//年龄范围异常
public class AgeRangeException extends Exception {
	public AgeRangeException(){
		 super("年龄不合法");
	}
	
	public AgeRangeException(String msg){
	  super(msg);
  }
}
import java.util.Scanner;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//请输入年龄,如果年龄不在1-100之间就抛出异常
		Scanner input=new Scanner(System.in);
		System.out.println("请输入年龄");
		int age=0;
		try {	
			age=input.nextInt();
			if(age>=100 || age<=1){
				//System.out.println("年龄输入错误");
		      //手动抛出错误
			  //throw new Exception("年龄输入错误,不在1-100之间");
		      throw new AgeRangeException("年龄输入错误,不在1-100之间");
			}
		} catch (Exception e) {
			//记录信息
			
			System.out.println("输入不区配:"+e.getMessage());
		}
			
		System.out.println(age);
	}

}

八、java中的自定义异常类型(了解)

定义一个子类去继承Exception类即可
例子:
public class AgeRangeException extends Exception {
public AgeRangeException(){
super(“年龄不合法”);
}

public AgeRangeException(String msg){
  super(msg);

}
}

九、采用工源日志记录工具(log4j)记录错误

1.使用log4j记录日志的步骤
a.在项目中导入log4j的jar包(log4j.jar)
在项目中新建lib目录,将log4j.jar包复制到lib目录,接着
在log4j.jar包上右键–>选择Bulid Path–>点击添加到bulid pat即可

b.创建log4j.properties属性文件,并存于src目录
作用:配置log4j如何工作

c.使用log4j记录日志
c.1创建记录器对象Logger
//在类中创建记录器对象
static Logger logger=Logger.getLogger(异常.class);

  c.2记录日志信息
 logger.info("错误信息");
 logger.debug("错误信息");
 logger.warn("错误信息");
 logger.error("错误信息");

集合框架

一、集合框架

1.java集合框架提供了一套性能优良、使用方便的接口和类,它们位于java.util(java工具包)包中.

2.java集合框架提供的接口及说明:
Collection->List、Set,Map接口
Collection接口存储一组不唯一,无序的对象
List接口存储一组不唯一,有序的对象
Set接口存储一组唯一(不许重复),无序的对象
Map接口存储一组键值对象,提供key到value的映射
注意;collection接口用来存储一组值的集合

3.使用集合的步骤:
3.1.导入相关集合接口及类
3.2.创建集合对象
3.3 使用集合对象相关方法操作集合

二、使用List接口

List接口的实现类:ArrayList、LinkedList

List接口常用方法:
add(元素) 添加元素
add(位置,元素) 在指定位置添加
size() 返回集合的长度
get(索引位置) 返回指定位置的元素
contains(元素) 判断某元素是否存在
remove(元素) 移除元素
remove(索引位置) 移除指定位置的字符

LinkedList的特殊方法(LinkedList在实现List后另添加的方法):
addFirst(元素) 在首位置加
addLast(元素) 在末位置加
removeFirst(元素) 在首位置移除
removeLast(元素) 在末位置移除
getFirst(元素) 取首位置值
getLast(元素) 取末位置值

代码示例:ArrayListDemo

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class ArrayListDemo {
	public static void main(String[] args) {
		//使用ArrayList集合存储一组学生姓名
		//1.创建集合对象
		List list=new ArrayList();  //面向接口编程
		//LinkedList list=new LinkedList(); 
		//2.使用集合对象的方法操作集合
		//2.1添加元素
		list.add("张三");
		list.add("李四");
		list.add("麻子");
		//2.2获取集合长度
		int len=list.size();
		System.out.println("长度为:"+len);
		//2.5移除集合元素
		//list.remove(1); //按位置移除
		list.remove("李四"); //按值移除
		//2.3获取集合某个位置的元素  位置从0开始
 		String str=(String)list.get(0);
 		System.out.println("值是"+str);
 		//2.4获取集合所有元素
	 	/*for (int i = 0; i < list.size(); i++) {
			System.out.println("值为:"+list.get(i));
		}*/
 	    Iterator iterator=list.iterator();
 	    while (iterator.hasNext()) {
			String strt = (String) iterator.next();
			System.out.println(strt);
		}
 		
 		//使用迭代器显示
	 	//2.6判断元素是否存在   存在返回true,反之false
		/*if(list.contains("麻1子"))
			System.out.println("存在");
		else
			System.out.println("不存在");*/
		
	}

}

代码示例:LinkedListDemo

import java.util.LinkedList;


public class LinkedListDemo {

	public static void main(String[] args) {
		//使用ArrayList集合存储一组学生姓名
		//1.创建集合对象
		LinkedList list=new LinkedList(); 
		//2.使用集合对象的方法操作集合
		//2.1添加元素
		list.add("张三");
		list.add("李四");
		list.add("麻子");
		//首尾添加
		list.addFirst("王二");
		//list.addLast("王二");
		//首尾移除
		//list.removeFirst();
		list.removeLast();
		//获取首尾位置的值
		System.out.println("第一个人名:"+list.getFirst());
		System.out.println("最后一名:"+list.getLast());
		//显示
		for (int i = 0; i <list.size(); i++) {
			System.out.println(list.get(i));
		}
	}

}

三、使用Set接口

Set接口的实现类:HashSet、TreeSet
类比list接口的使用方法
代码示例:HashSetDemo

import java.util.HashSet;
import java.util.Set;

public class HashSetDemo {
	public static void main(String[] args) {
       //使用Hashset存储一组学生姓名
		//创建集合
		Set set=new HashSet();
		 //操作集合元素
		set.add("张三");
		set.add("麻子");
		//set.add("麻子");  //添加重复值时发生替换
		//移除
		//set.remove("麻子");
		System.out.println("大小为:"+set.size());
		//使用迭代器循环集合
		//1.创建迭代器
		//Iterator iterator=set.iterator();
		//iterator.hasNext()判断有没有下一个元素 有返回true,没有返回false
		//iterator.next(); //可以下一个元素
		/*while(iterator.hasNext()){
			String str=(String)iterator.next();  //获取值
		    System.out.println(str);
		}*/
		
		//增强for循环(foreach循环)
		//for(数据类型 变量名:集合|数组){
			 //注意:变量名在循环过程代表集合中的每个元素
		//}
	for (Object o : set) {
		System.out.println("值为"+o);
	}
		
	}

}

四、循环集合的方法

1.使用迭代器(Iterator)循环集合
使用迭代器的步骤:
a.基于集合创建迭代器对象
Iterator iterator=set.iterator();
b.使用hasNext方法和next方法读取元素
hasNext() 判断有没有下一元素 有返回true,没有返回false
next()获取一个元素
示例:
Iterator iterator=集合.iterator();
while(iterator.hasNext()){
String str=(String)iterator.next();
System.out.println(str);
}

2.增强for循环(foreach循环)
for(数据类型 变量名:集合|数组){
//注意:变量名在循环过程代表集合中的每个元素
}

五、使用Map接口

Map接口的实现类:HashMap、TreeMap

   //创建集合   
   Map map=new HashMap();
   //添加值
   map.put("ABC", "中国农业银行");
   map.put("ICBC", "中国工商银行");
   map.put("CCB", "中国建设银行");
   //map.put("CCB", "中国招商银行");  //替换
   //移除某元素
   map.remove("CMB");
  //获取长度
   System.out.println("长度:"+map.size());
  //获取某个元素的值
  System.out.println("值为:"+map.get("CCB")); 
  //获取键值对集合的所有值
	  //获取所有键  map.keySet()
	  /*for (Object key : map.keySet()) {
		System.out.print("键为:"+key);
		System.out.println("值为:"+map.get(key));
	  }*/
	  //获取所有值  map.values()
	 for (Object v :  map.values()) {
		System.out.println(v);
	 }
	 
	 //判断键是否存在
	if( map.containsKey("CCB"))
		System.out.println("存在");
	else
		System.out.println("不存在");

**代码示例:HashMapDemo **


import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {
  public static void main(String[] args) {
	 //存一组银行名称及代码
	 //键(key)==>值(value)    键值对
	  
	  //创建键值对集合 键不能重复,值可重复
	  Map map=new HashMap();
	  //添加值
	  map.put("ABC", "中国农业银行");
	  map.put("ICBC", "中国工商银行");
	  map.put("CCB", "中国建设银行");
	  //map.put("CCB", "中国招商银行");  //替换
	  //移除某元素
	  //map.remove("CMB");
	  //获取长度
	  System.out.println("长度:"+map.size());
	  //获取某个元素的值
	  System.out.println("值为:"+map.get("CCB"));
	  //获取键值对集合的所有值
	  //获取所有键  map.keySet()
	  /*for (Object key : map.keySet()) {
		System.out.print("键为:"+key);
		System.out.println("值为:"+map.get(key));
	  }*/
	  //获取所有值  map.values()
	 for (Object v :  map.values()) {
		System.out.println(v);
	 }
	 
	 //判断键是否存在
	if( map.containsKey("CCB"))
		System.out.println("存在");
	else
		System.out.println("不存在");
}
}

六、泛型集合

1.所谓泛型就是泛指某一类型
注意:泛型只能是引用类型(类类型)
2.使用泛型集合
Map<String, String> mps=new HashMap<String, String>();
List list2=new ArrayList();
代码示例

import java.util.HashMap;
import java.util.Map;
public class Test {
 public static void main(String[] args) {
	//使用泛型集合存银行信息
	 Map<String, String> bank=new HashMap<String, String>();
	 //存
	 bank.put("ABC", "农行");
	 bank.put("ICBC", "工商");
	 //...
	 //显示
	 for (String key :  bank.keySet()) {
		System.out.println("键是:"+key);
		System.out.println("值是:"+bank.get(key));
	}
	
}
}

java文件操作

java常用的包
java.util 工具包
java.lang java基础类(常用数据类型)
java.io 操作文件
java.awt 或 java.swing 开发桌面程序(c# window)

一、什么是文件

文件可认为是相关记录或放在一起的数据集合
注意:硬盘只能存各种文件(文件扩展名是用来区分文件)
java操作文件需要用到:java.io包

二、使用File操作文件或目录目骤

1.创建File类的对象关联文件
File file=new File(“关联文件路径”);

2.使用File类的对象的方法操作文件
exists() 判断文件是否存在
isFile() 判断是不是文件
isDirectory() 判断是不是目录
getPath() 获取文件的路径
getName() 获取文件的名称
delete() 删除文件
createNewFile() 创建文件
mkdir() 创建文件夹
length() 获取文件大小以字节为单位
listFiles() 获取目录下所有文件
代码示例
文件操作

import java.io.File;
import java.io.IOException;
public class 文件操作 {
 public static void main(String[] args) {
    //使用file类
	//创建文件对象
	 //注意:一个File类的对象即为一个文件
	 File file=new File("d:\\DT25.txt");//d:/DT25.txt
     //文件相关方法
	 try {
		 //判断文件是否存  存在返回true,反之false
		 if(file.exists())
		 {
			 System.out.println("文件已存在");
			 //删除文件
			 file.delete();
			 System.out.println("删除成功...");
		 }else
		 {
			 //创建文件
			file.createNewFile();
			System.out.println("创建文件成功");
		 }
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
 }
	
}

文件夹操作

import java.io.File;

public class 文件夹操作 {
  public static void main(String[] args) {
	  //文件夹管理
	  File file=new File("D:\\DT25"); 
	  if(file.exists())
	  {
		  System.out.println("存在文件夹");
		  file.delete();   //为空目录
		  System.out.println("删除成功");
	  }
	  else
	  {
	  file.mkdir();  //创建文件夹
	  System.out.println("创建成功");
	  }
	 }
}

获取文件相关属性:在D盘下放一个图片文件

import java.io.File;
import java.util.Date;

public class 获取文件相关属性 {
 public static void main(String[] args) {
	File file=new File("D:\\15.jpg");
	
	System.out.println("文件名是:"+file.getName());
    System.out.println("文件大小:"+file.length()+"字节");
    System.out.println("文件路径:"+file.getPath());
    System.out.println("是不是文件:"+file.isFile());
    System.out.println("是不是目录:"+file.isDirectory());
    System.out.println("是否隐藏:"+file.isHidden());
    System.out.println("文件修改时间:"+new Date(file.lastModified()));
 }
}

java实现文件复制


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class 实现文件复制 {
  public static void main(String[] args) {
	  Scanner input=new Scanner(System.in);
	  System.out.println("请输入d盘下的文件 :");
	  String sourceFile=input.next();
	  System.out.println("复到E盘下目标文件名:");
	  String targetFile=input.next();
	  
	 //复制边读边写
	  try {
		  //输入流 读文件
		FileInputStream fis=new FileInputStream("d:\\"+sourceFile);
		  //输出流 写文件
		FileOutputStream fos=new FileOutputStream("E:\\"+targetFile);
		  //边读边写
		 int c;
		 while((c=fis.read())!=-1){//读
		  fos.write(c);  //写	 
		 }
	     //关闭流
		 fis.close();
		 fos.close();
		 System.out.println("复制成功");
	  } catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	  
  }
}

示例读取某目录下的文件

import java.io.File;

public class 示例读取某目录下的文件 {
 public static void main(String[] args) {
	File d=new File("D:\\");
	//获取目录下所有文件
    File [] files=d.listFiles();
    System.out.println("类型\t大小\t名称");
    for (File file : files) {
	   if(file.isFile())
		   System.out.print("文件\t");
	   else
		   System.out.print("文件夹\t");
	   
	   System.out.print(file.length()+"\t");
	   
	   System.out.println(file.getName());
	}
}
}

三、使用流(Stream)技术读写文件

1.什么是流
流是指一连串流动的字符,是以先进先出方式发送信息的通道.

2.按流向区分:
输出流:OutputStream和Writer作为基类
作用:写文件
输入流:InputStream和Reader作为基类
作用:读文件

3.按处理数据单元划分
字节流(不支持中文):输入流InputStream和输出流outputStream
字符流(支持中文):Writer输出流和Reader输入流
注意:字节流是8位通用字节流
字符流是16位Unicode字符流

4.读写文件的步骤;
4.1创建相应的流对象
4.2进行相关读写操作
读 read方法
写 write方法
4.3关闭流对象

5.使用
FileInputStream读
FileOutputStream写
代码示例
FileInputStream读文件


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStream读文件 {
	public static void main(String[] args) {	
		try {
			  //1.创建流对象
			FileInputStream fis=new FileInputStream("D:\\DT25.txt");
		      //2.读操作
			//int c=fis.read();  //一次读一个字节
			//System.out.println((char)c);
			
			//循环读所有内容
			/*int c; 
			while((c=fis.read())!=-1){
				System.out.print((char)c);
			}*/
			
			 //读以字节数组
			//fis.available()  获取文件大小  字节为单位
			byte [] bs=new byte[fis.available()];  //文件字节数
			fis.read(bs);
			System.out.println(new String(bs));
			
			//3.关闭
			fis.close();	
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

FileOutputStream写文件


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStream写文件 {
  public static void main(String[] args) {
	  try {
		//1.创建流
		FileOutputStream fos=new FileOutputStream("d:\\DT25.txt",true); //表示追加内容
	    //2.写内容
	    //fos.write('c');   //写入单个字符
		 //定入字节数组
		String str="hello:王建兵";
		byte[] bs=str.getBytes();
		fos.write(bs);
		//3.关闭
		fos.close();
		System.out.println("写入成功");
	  } catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	  
}
}

四、字符串与字节数组的转换

1.将字符串转化为字节数组
byte[]bs=字符串.getBytes();

2.将字节数组转化为字符串
String str=new String(字节数组);

文件操作字符流和反序列化

一、字符流

FileWriter 写文件
FileReader 读文件

带缓冲区的字符串流
BufferedWriter
注意:支持换行方法
BufferedReader
注意:支持读一行方法


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderDemo {

	
	public static void main(String[] args) {
		//按行读取
		FileReader fr=null;
		BufferedReader br=null;
		try {
			fr = new FileReader("D:\\DT25.txt");
			br=new BufferedReader(fr);
			//读文件
			String line;
			while((line=br.readLine())!=null){
				System.out.println(line);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
				try {
					if(br!=null) br.close();
					if(fr!=null) fr.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	
		

	}

}

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriteDemo {
  public static void main(String[] args) {

	try {
		//1.创建流对象
	    FileWriter fw=new FileWriter("d:\\DT25.txt");
	    BufferedWriter bw=new BufferedWriter(fw);
	    //2写操作
		 bw.write("我的姓名:王建兵");
		 bw.newLine();  //换行
	     bw.write("性别是:女");
	     bw.newLine();  //换行
	     bw.write("地址:武汉汉阳");
	    //3.关闭流
        bw.flush();  //清空缓冲区  针对写操作 
        bw.close();
        fw.close();
        System.out.println("写入成功");
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	  
	  
}
}

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo {
 public static void main(String[] args) {
	try {
		FileReader fr=new FileReader("D:\\DT25.txt");
	    //读一个字符
		//int c=fr.read();
		//System.out.println((char)c);
	    //读所有
		int c;
		while((c=fr.read())!=-1){
			System.out.print((char)c);
		}
		
        fr.close();
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
}
}

import java.io.FileWriter;
import java.io.IOException;

public class FileWriteDemo {
  public static void main(String[] args) {

	try {
		//1.创建流对象
		//File f=new File("D:\\DT25.txt");
		//FileWriter fw=new FileWriter(f,true);
		FileWriter fw=new FileWriter("D:\\DT25.txt");
	    //2写操作
		fw.write("我的姓名:王建兵");
	    fw.write("性别是:女");
	    //3.关闭流
        fw.flush();  //清空缓冲区  针对写操作 
        fw.close();
        System.out.println("写入成功");
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	  
	  
}
}

二、如何让文本文件有规律的存储数据?

存一个学生信息:姓名,年龄,性别
解决方法:
一行一个对象相关信息,而对象的信息用分隔符隔开

学生管理系统:
1.添加 2.查询

代码示例


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;

public class 添加学生 {
  public static void main(String[] args) {
	Scanner input=new Scanner(System.in);
	System.out.println("请输入姓名:");
	String name=input.next();
	System.out.println("请输入姓别:");
	String sex=input.next();
	System.out.println("请输入年龄");
	int age=input.nextInt();
	
	//存
	try {
		FileWriter fw=new FileWriter("D:\\stulist.txt",true);
		BufferedWriter bw=new BufferedWriter(fw);
		//写数据
		String info=name+"|"+sex+"|"+age;
		bw.write(info);
		bw.newLine(); //换行
		bw.flush();
		bw.close();
		fw.close();
		System.out.println("保存成功");
	} catch (Exception e) {
		// TODO: handle exception
	}

	
	
}
}


import java.io.BufferedReader;
import java.io.FileReader;

public class 读取学生信息 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
      //读文件
		try {
			FileReader fr=new FileReader("D:\\stulist.txt");
			BufferedReader br=new BufferedReader(fr);
			
			System.out.println("姓名\t性别\t年龄");
			//读一行
			String str;
			while((str=br.readLine())!=null){
				//分割字符串 
				String []ary=str.split("\\|");
				System.out.print(ary[0]+"\t");
				System.out.print(ary[1]+"\t");
				System.out.println(ary[2]);	
			}
			
			br.close();
			fr.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	
	}

}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
//一个管理系统一个类
public class StuMan {
	Scanner input=new Scanner(System.in);
   //一个功能一方法
	public void mainFace(){
		 System.out.println("欢迎使用本系统:");
		 System.out.println("1.添加学生  2.查询学生");
	     System.out.print("请输择功能:");
	     int i=input.nextInt();
	     switch (i) {
			case 1:
				 this.addStudent();
				break;
			case 2:
				this.showStudent();
				break;
		}
	}
	
	/**
	 * 添加学生
	 */
	public void addStudent(){
		System.out.println("请输入姓名:");
		String name=input.next();
		System.out.println("请输入姓别:");
		String sex=input.next();
		System.out.println("请输入年龄");
		int age=input.nextInt();
		
		//存
		try {
			FileWriter fw=new FileWriter("D:\\stulist.txt",true);
			BufferedWriter bw=new BufferedWriter(fw);
			//写数据
			String info=name+"|"+sex+"|"+age;
			bw.write(info);
			bw.newLine(); //换行
			bw.flush();
			bw.close();
			fw.close();
			System.out.println("保存成功");
		} catch (Exception e) {
			// TODO: handle exception
		}

		System.out.println("是否想回主菜单");
		String s=input.next();
		if(s.equals("y"))
			this.mainFace();
		else
			this.addStudent();
	}
	
	/**
	 * 查询学生
	 */
	public void showStudent(){
		   //读文件
				try {
					FileReader fr=new FileReader("D:\\stulist.txt");
					BufferedReader br=new BufferedReader(fr);
					
					System.out.println("姓名\t性别\t年龄");
					//读一行
					String str;
					while((str=br.readLine())!=null){
						//分割字符串 
						String []ary=str.split("\\|");
						System.out.print(ary[0]+"\t");
						System.out.print(ary[1]+"\t");
						System.out.println(ary[2]);	
					}
					
					br.close();
					fr.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
			
				System.out.println("是否想回主菜单");
				String s=input.next();
				if(s.equals("y"))
					this.mainFace();
				else
					this.showStudent();
	}
	
	
}

main函数


public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		  StuMan sm=new StuMan();
		  sm.mainFace();
	}

}

三、[理解]java中的序列化机制|反序列化

注意:实现Serializable 接口的类才支持序列化
例如:
public class Student implements Serializable { //支持序列

}

1.序列化:将java对象以文件的形势进行保存
//创建一个学生对象
Student stu=new Student();
stu.setName(“王二”);
stu.setAge(100000);
stu.setSex(“人妖”);

  //序列化 (写)
  try {
	  OutputStream os=new FileOutputStream("d:\\h.txt");
	  ObjectOutputStream sos=new ObjectOutputStream(os);
	  //写对象
	  sos.writeObject(stu);
	  sos.close();
	  os.close();
	  System.out.println("保存");
} catch (Exception e) {
	// TODO: handle exception
}

2.反序列化:将文件中的数据还原成java对象
InputStream os=new FileInputStream(“d:\h.txt”);
ObjectInputStream ois=new ObjectInputStream(os);
//写对象
Student stu=(Student)ois.readObject();
ois.close();
os.close();
代码示例
反序列化


import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;

public class 理解反序列化 {
  public static void main(String[] args) {
	  //序列化 (写)
	  try {
		  InputStream os=new FileInputStream("d:\\h.txt");
		  ObjectInputStream ois=new ObjectInputStream(os);
		  //写对象
		  Student stu=(Student)ois.readObject(); 
		  ois.close();
		  os.close();

		  System.out.println("学生姓名:"+stu.getName());
		  System.out.println("年龄:"+stu.getAge());
		  System.out.println("性别:"+stu.getSex());
		  
		  

	} catch (Exception e) {
		// TODO: handle exception
	}

序列化


import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class 理解序列化 {
  public static void main(String[] args) {
	 //创建一个学生对象
	  Student stu=new Student();
	  stu.setName("王二");
	  stu.setAge(100000);
	  stu.setSex("人妖");

	  //序列化 (写)
	  try {
		  OutputStream os=new FileOutputStream("d:\\h.txt");
		  ObjectOutputStream sos=new ObjectOutputStream(os);
		  //写对象
		  sos.writeObject(stu);
		  sos.close();
		  os.close();
		  System.out.println("保存");
	} catch (Exception e) {
		// TODO: handle exception
	}
	  
	 
}
}
import java.io.Serializable;

//学生类
public class Student implements Serializable { //支持序列
   
private String name;
   private String sex;
   private int age;
   public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

java字符串处理

一、创建字符串对象

方式一:
String str=“字符串”;
方式二:
String str=new String();
String str=new String(“字符串”);

二、常用字符串处理方法

1.获取字符串长度
字符串对象.length();
2.将字符串转化为大写
字符串对象.toUpperCase();
3.将字符串转化为小写
字符串对象.toLowerCase();
4.比较字符串是否相等 区分大小写
字符串对象.equals(比较的字符串);
5.比较字符串是否相等 不区分大小写
字符串对象.equalsIgnoreCase(比较的字符串);
6.查找某字符在字符串中首次出现的位置
字符串对象.indexOf(要查找的字符);
注意:如果找不到返回-1,找到返回位置(从0开始算)
7.返着查找某字符在字符串中首次出现的位置
字符串对象.lastIndexOf(要查找的字符);
注意:返着找从左往右算位置
8.截取子字符串
字符串对象.subString(开始位置)
字符串对象.subString(开始位置,结束位置)
9.获取指定位置的字符
字符串对象.charAt(指定位置);
10.去除字符串左右两边的空格
字符串对象.trim();
11.替换字符串
字符串对象.replace(“旧字符串”,“新字符串”);
12.分割字符串
字符串对象.split(分割符); //返回数组

三、==与equals区别(面试经常问到)

==用来判断字符串对象是否相同
equals判断两字符内容是否相同

四、StringBuffer类

它是String的增强类,提供符串本身的操作
创建Stringbuffer字符串
//StringBuffer sb=new StringBuffer(“字符串”);
StringBuffer sb=new StringBuffer(“a”);
//2.使用方法处理字符串
//2.1追加
sb.append(“b”);
sb.append(“c”);
sb.append(“d”);
//2.2删除字符
sb.deleteCharAt(2);
//2.3反转字符串
sb.reverse();
//2.4将stringbuffer转化为string
String str= sb.toString();
代码示例

java字符串处理:字符串处理相关方法

public class Test {

	public static void main(String[] args) {
       //定义字符串
	   String str1="abcdeafg";  //当作变量定义
	   //String str=new String();  //创建字符串对象 对象为""
	  String str=new String("AbC");
	  String str2=str1;
	
		//2.字符串常用方法
		//1.获取字符串长度
	   int len=str.length();
	   System.out.println("字符串长度为:"+len);
	   
	    //2.比较字符串
	  // if(str1==str2)  //判断两字符是否为同一对象
	   if(str1.equals(str))  //判断两字符内容是否相同
	   System.out.println("相等");
	   else
		System.out.println("不相等");
	   
	   //3.将字符串转化为大写
	  String ustr=str.toUpperCase();  //ABC
	  System.out.println(ustr);
	   //4.将字符串转化为小写
	  String lstr=str.toLowerCase();
	  System.out.println(lstr);
	  
	  //5.连接字符串
	  //字符串1.concat(字符串2);
	  String java="90";
      String info="java成绩:";
	  System.out.println(info.concat(java));
	   
	  //6.查询字符或字符串在另一个字符串中首次出现的位置
	  //理解类:判断某字符串另外一个字串中是否有出现
	  //int pos=str1.indexOf("bc");  //从前往后找
	  int pos=str1.lastIndexOf("a");  //从后往前找
	  System.out.println("位置是:"+pos);
	  
	  
	  //7.截取子字符串
	  String str3="abcdefg";
	  //String cstr=str3.substring(2); //从指定位置开始截取到最后
	  String cstr=str3.substring(3,4); //从1开始到4结束
	  System.out.println(cstr);
	  //截取每个字符
	  /*for(int i=0;i<str3.length();i++){
		System.out.println(str3.substring(i,i+1));
	  }*/
	  
	  //8.获取指定位置的字符
	   char c= str3.charAt(3);
      System.out.println("字符是:"+c);
      for(int i=0;i<str3.length();i++){
  		System.out.println(str3.charAt(i));
  	  }
      
      //9.去除字符中空格
      String str4=" a b c ";
     String str5= str4.trim(); //去除字符串左右两边的空格
     System.out.println("去除空格后内容是:"+str5);
     System.out.println(str5.length());
      
     //10.分割字符串
     String str6="张三,李四,麻子";
     String [] slist=str6.split(",");  //用逗号去分割字符串
     for (int i = 0; i < slist.length; i++) {
	 	System.out.println(slist[i]);
	}
     
     //11.替换
     String str7="abcabcabc"; //b=>B
    String nstr=str7.replace("b", "B");
     System.out.println("替换后:"+nstr);
     

	}

}

java字符串处理:查找字符在字符串中出现的次数


import java.util.Scanner;

public class Test5 {
	public static void main(String[] args) {
      Scanner input=new Scanner(System.in);
      System.out.println("请输入字符串:");
      String str=input.next(); //"abcabc"
      System.out.println("请输入查找字符:");
      String selstr=input.next(); //"c"
      int j=0;  //累加器
      //循环
      for(int i=0;i<str.length();i++){
    	String cstr=str.substring(i,i+1);
    	if(selstr.equals(cstr)){
    		j++;
    	}
    	 /*char c= str.charAt(i);
    	 if(selstr.equals(c+"")){
    		 j++;
    	 }*/
    	/* if(selstr.charAt(0)==c){ 
    		  j++;
    	 }*/
    	 
      }
      System.out.println("\""+str+"\"中出现"+selstr+"个数为:"+j);
	}

}

java字符串处理:判断输入密码的长度


import java.util.Scanner;

public class Test4 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner input=new Scanner(System.in);
		System.out.println("输入密码:");
		String str=input.next();
		if(str.length()>=6)
			System.out.println("输入正确");
		else
			System.out.println("输入不合法");
		

	}

}

java字符串处理:判断用户名是否含有指定字符


import java.util.Scanner;

public class Test3 {

	public static void main(String[] args) {
         //验证用户名是否含有@
		Scanner input=new Scanner(System.in);
		System.out.println("请输入用户名:");
		String str=input.next();  //abc
		
		int pos=str.indexOf("@");
		
		if(pos==-1){
			System.out.println("不合法;没有@符号");
		}else
		{
			System.out.println("合法");
		}
		
		
	}

}

**java字符串处理:判断邮箱格式是否正确 **


import java.util.Scanner;

public class Test2{


	public static void main(String[] args) {
		 Scanner input=new Scanner(System.in);
		 System.out.println("请输入邮箱格式:");
		 String str=input.next(); //fgh.jdf@.sd
		 //判断
		 int pos=str.indexOf("@");
		 int pos1=str.lastIndexOf(".");
		 
		 if(pos==-1 ||pos1==-1||(pos1-pos)<=1){
			 System.out.println("格式不正确");
		 }else
		 {
			 System.out.println("正确");
		 }
		 
		 

	}

}

java字符串处理:实现用户登入


import java.util.Scanner;

public class Test1 {

	public static void main(String[] args) {
      //用户名输入admin 密码为:123
		Scanner input=new Scanner(System.in);
		System.out.println("请输入用户名:");
		String name=input.nextLine();
		System.out.println("请输入密码:");
		String pwd=input.next();
		
		//if(name.toLowerCase().equals("admin")&&pwd.equals("123"))
		//if(name.toUpperCase().equals("ADMIN")&&pwd.equals("123"))
		 //equalsIgnoreCase不区分大小写比较
		if(name.trim().equalsIgnoreCase("admin")&&pwd.equals("123"))
		{
			System.out.println("登入成功");
		}
		else
			System.out.println("登入失败");
		
	}

}

java字符串处理:转化日期格式


public class Test {

	public static void main(String[] args) {
      String str="2015-3-23";//
      //实现转化=>2015.3.23
      //String newstr= str.replace("-","/");
     // System.out.println(newstr);
      
      //实现转化=>2015年3月23号
      //拆--拼
      //拆
     String datepart[]=str.split("-");
    /* System.out.println(datepart[0]);
     System.out.println(datepart[1]);
     System.out.println(datepart[2]);
   */
     //拼字符串  效率低
    // String newdate=datepart[0]+"年"+datepart[1]+"月"+datepart[2]+"号";
     
     //使用StringBuffer拼接字符串   效率高
     StringBuffer sb=new StringBuffer();
     sb.append(datepart[0]);
     sb.append("年");
     sb.append(datepart[1]);
     sb.append("月");
     sb.append(datepart[2]);
     sb.append("号");
     
     System.out.println(sb.toString());
	}

}

**java字符串处理:StringBufferDemo **

public class StringBufferDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
    //创建Stringbuffer字符串
	 //StringBuffer sb=new StringBuffer("字符串");
	  StringBuffer sb=new StringBuffer("a");
	  //2.使用方法处理字符串
	  //2.1追加
	  sb.append("b");
	  sb.append("c");
	  sb.append("d");
	  //2.2删除字符
	  sb.deleteCharAt(2);
	  //2.3反转字符串
	  sb.reverse();
	  //2.4将stringbuffer转化为string
	 String str= sb.toString();
	 
	  System.out.println(str);

	}

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值