------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
●File类
用来将文件或者文件夹封装成对象
方便对文件与文件夹进行操作
File对象可以作为参数传递给流的构造函数
了解File类中的常用方法
public static void main(String[] args) {
File file1 = new File("a.txt");
File file2 = new File("g:/","a.txt");
File d = new File("g:/");
File file3 = new File(d,"a.txt");
}
●File类常见方法
(1)创建
BooleancreatNewFile();在指定位置创建文件,如果该文件已经存在,则不创建,返回false,和输出流不一样,输出流对象一建立创建文件,而且文件已经存在,会覆盖
booleanmkdir();创建文件夹
Booleanmkdirs()创建多级文件夹
(2)删除
Booleandelete();删除失败返回false
voiddeleteOnExit();在程序退出时删除指定文件
(3)判断
Booleanexist();文件是否存在
PS:在判断文件对象是否是文件或者目录时,必须要先判断该文件对象封装的内容是否存在
isFile();
isDirectory()
isHidden();
isAbsolute();
(4)获取信息
getName()
getPath()
getParent()该方法返回的是绝对路径中的父目录,如果获取的是相对路径,返回nul,如果相对路径中有上一层目录,该目录就是返回结果
getAbsolutePath()
longlastModified()
longlength()
(5)重命名 renameTo()
(6)获取盘符File.listRoots()
(7)list()调用list方法的file对象必须是封装了一个目录,该目录还必须存在
●list带过滤器
public static void main(String[] args) {
File file = new File("g:/");
String[] list = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir,String name) {
return name.endsWith(".jpg");
}
});
for(String name:list){
System.out.println(name);
}
}
●遍历文件
public static void ergodic(File f){
File[] listFiles = f.listFiles();
for (int i = 0; i < listFiles.length; i++) {
if(listFiles[i].isDirectory()){
System.out.println(listFiles[i].toString());
ergodic(listFiles[i]);
}else{
System.out.println(listFiles[i].toString());
}
}
}
●递归
public static int getSum(int n){
if(n==1)
return 1;
return n+getSum(--n);
}
递归要注意:
(1)限定条件
(2)要注意递归的次数,要尽量避免内存溢出
●删除文件夹
public static void myDelete(File file){
File[] listFiles = file.listFiles();
for (int i = 0; i < listFiles.length; i++) {
if(listFiles[i].isDirectory())
{
myDelete(listFiles[i]);
}else{
listFiles[i].delete();
}
}
System.out.println(file.delete());
}
●创建java文件列表
public class FileJavaDemo {
static List<File> list = new ArrayList<File>();
public static void main(String[] args) throws IOException {
File file = new File("g:/app");
FileToList(file,list);
writeToFile(list,"g:/javaFile.txt");
}
public static void FileToList(File file,List<File> list){
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if(files[i].isDirectory())
{
FileToList(files[i],list);
}else{
if(files[i].toString().endsWith(".java"))
list.add(files[i]);
}
}
}
public static void writeToFile(List<File> list,String javaListFile) throws IOException{
BufferedWriter bw = new BufferedWriter(new FileWriter(javaListFile));
for (int i = 0; i < list.size(); i++) {
bw.write(list.get(i).toString());
bw.newLine();
bw.flush();
}
if(bw!=null)
bw.close();
}
}
●Properties
Properties是hashtable的子类
也就是说它具备map集合的特点,而且它里面存储的键值对都是字符串
是集合中和IO技术相结合的集合容器
该对象的特点:可以用于键值对形式的配置文件
public static void main(String[] args) throws IOException {
Properties pro = new Properties();
pro.load(new FileReader("g:/Properties.txt"));
pro.list(System.out);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("g:/Properties.txt"));
Properties pro = new Properties();
String line =null;
while((line=br.readLine())!=null){
String[] split = line.split("=");
pro.setProperty(split[0], split[1]);
}
br.close();
pro.list(System.out);
}
●properties练习
public class PropertiesDemo3 {
public static void main(String[] args) throws IOException {
Properties pro = new Properties();
File file = new File("g:/count.properties");
if(!file.exists())
file.createNewFile();
FileInputStream fis = new FileInputStream(file);
pro.load(fis);
int count = 0;
String value = pro.getProperty("time");
if(value!=null){
count=Integer.parseInt(value);
if(count>=5){
System.out.println("注册吧!");
return;
}
}
count++;
pro.setProperty("time", count+"");
FileOutputStream fos = new FileOutputStream(file);
pro.store(fos,"");
fis.close();
fos.close();
}
}
●打印流
提供了打印方法,可以将各种数据类型的数据都原样打印
字节打印流:PrintStream
构造函数可以接收的参数类型
file对象 File
字符串路径:String
字节输出流:OutputStream
字符打印流:PrintWrite
构造函数可以接收的参数类型
file对象 File
字符串路径:String
字节输出流:OutputStream
字符输出流:Writer
●PrintWriter
public static void main(String[] args) throws IOException {
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out,true);
String line = null;
while((line=br.readLine())!=null){
if("over".equals(line))
break;
out.println(line.toUpperCase());
}
br.close();
out.close();
}
●序列流
SequenceInputStream(
InputStream s1,
InputStream s2)
public static void main(String[] args) throws IOException {
Vector<FileInputStream> v = new Vector<FileInputStream>();
v.add(new FileInputStream("g:/1.txt"));
v.add(new FileInputStream("g:/2.txt"));
v.add(new FileInputStream("g:/3.txt"));
Enumeration<FileInputStream> elements = v.elements();
SequenceInputStream sis = new SequenceInputStream(elements);
InputStreamReader isr = new InputStreamReader(sis);
BufferedReader br = new BufferedReader(isr);
FileWriter fw = new FileWriter("g:/hebing.txt");
String line=null;
while((line=br.readLine())!=null){
fw.write(line+"\r\n");
fw.flush();
}
fw.close();
br.close();
}
●切割流
public static void splitFile() throws IOException{
FileInputStream fis = new FileInputStream("g:/renxi.mp3");
FileOutputStream fos = null;
int num = 1;
byte[] buf = new byte[1024*1024];
int len = 0;
while((len=fis.read(buf))!=-1){
fos= new FileOutputStream("g:/"+num+".part");
fos.write(buf,0,len);
num++;
fos.close();
}
fis.close();
}
public static void merge() throws IOException{
ArrayList<FileInputStream> al = newArrayList<FileInputStream>();
for (int i = 1; i <= 5; i++) {
al.add(new FileInputStream("g:/"+i+".part"));
}
final Iterator<FileInputStream> iterator =al.iterator();
Enumeration<FileInputStream> en = newEnumeration<FileInputStream>() {
@Override
public FileInputStream nextElement() {
return iterator.next();
}
@Override
public boolean hasMoreElements() {
// TODO Auto-generatedmethod stub
return iterator.hasNext();
}
};
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream("g:/xiren.mp3");
byte[] buf = new byte[1024*1024];
int len = 0;
while((len=sis.read(buf))!=-1){
fos.write(buf,0,len);
}
fos.close();
sis.close();
}
●操作对象
ObjectInputStream与ObjectOutputStream被操作的对象需要实现Serializable(标记接口)没有方法的接口 ,称为标记接口
transient int age;//不被序列化
public static String country = "cn";//static 不在堆内存 不能被序列化
class Student implements Serializable{
public static final long serialVersionUID = 42L;
private String name;
transient int age;
public static String country = "cn";
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student[age=" + age + ",name=" + name + "]";
}
}
public class ObjectDemo {
public static void main(String[] args) throws FileNotFoundException,IOException, ClassNotFoundException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("g:/object.txt"));
oos.writeObject(new Student("zhangsan", 20));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("g:/object.txt"));
Student student = (Student)ois.readObject();
System.out.println(student);
}
}
●管道流
PipedInputStream和PipedOutputStream涉及到多线程的IO流技术
class readDemo implements Runnable{
private PipedInputStream in ;
public readDemo(PipedInputStream in) {
super();
this.in = in;
}
@Override
public void run() {
try {
byte[] buf = new byte[1024];
int len = in.read(buf);
String s = new String(buf,0,len);
System.out.println(s);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class writeDemo implements Runnable{
private PipedOutputStream out ;
public writeDemo(PipedOutputStream out) {
super();
this.out = out;
}
@Override
public void run() {
try {
out.write("shu ju laila!".getBytes());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class PipedStreamDemo {
public static void main(String[] args) throws IOException {
PipedInputStream pipedInputStream = newPipedInputStream();
PipedOutputStream pipedOutputStream = newPipedOutputStream();
pipedInputStream.connect(pipedOutputStream);
readDemo readDemo = new readDemo(pipedInputStream);
writeDemo writeDemo = new writeDemo(pipedOutputStream);
Thread thread1 = new Thread(readDemo);
Thread thread2 = new Thread(writeDemo);
thread1.start();
thread2.start();
}
}
●RandomAccessFile(多个线程分段写入一个文件)
该类不算是IO体系中子类,而是直接继承自Object。
但是它是IO包中成员,因为它具备读和写功能
内部封装了一个数组,而且通过指针对数组的元素进行操作
可以通过getFilePointer获取指针位置,
同时可以通过seek改变指针的位置
其实完成读写的原理就是内存封装了字节输入流和输出流
通过构造函数可以看出,该类只能操作文件
而且操作文件还有模式,只读r,读写rw等
而且该对象的构造函数要操作的文件不存在,会自动创建,如果存在不会覆盖
如果模式为只读r。不会创建文件 会去读取一个已存在的文件,如果该文件不存在,则会出现异常
如果模式为rw,而且该对象的构造函数要操作的文件不存在,会自动创建,如果存在不会覆盖
public class RandomDemo {
public static void main(String[] args) throws IOException {
readDemo();
//writeDemo();
}
public static void writeDemo() throws FileNotFoundException, IOException {
RandomAccessFile raf = new RandomAccessFile("g:/ran.txt", "rw");
raf.write("李四".getBytes());
raf.writeInt(97);
raf.write("王五".getBytes());
raf.writeInt(22);
raf.close();
}
public static void readDemo() throws FileNotFoundException, IOException {
RandomAccessFile raf = new RandomAccessFile("g:/ran.txt", "r");
int readInt;
raf.seek(8);
raf.skipBytes(8);
byte[] buf = new byte[4];
readInt= raf.read(buf);
System.out.println(new String(buf));
readInt = raf.readInt();
System.out.println(readInt);
raf.close();
}
}
●IO包中的其他类
★DataInputStream 与 DataOutputStream可以用于操作基本数据类型的数据的流对象
writeUTF(Stringstr);
public class DataStreamDemo {
public static void main(String[] args) throws IOException {
readUTFDemo();
}
public static void readStream() throws IOException{
DataInputStream dis = new DataInputStream(new FileInputStream("g:/data.txt"));
int readInt = dis.readInt();
boolean readBoolean = dis.readBoolean();
double readDouble = dis.readDouble();
System.out.println(readInt);
System.out.println(readBoolean);
System.out.println(readDouble);
}
public static void writeData() throws IOException{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("g:/data.txt"));
dos.writeInt(369);
dos.writeBoolean(true);
dos.writeDouble(23.56);
}
public static void writeUTFDemo() throws IOException{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("g:/UTF.txt"));
dos.writeUTF("你好\r\n中午好");
dos.close();
}
public static void readUTFDemo() throws IOException{
DataInputStream dis = new DataInputStream(new FileInputStream("g:/UTF.txt"));
String readUTF = dis.readUTF();
dis.close();
System.out.println(readUTF);
}
}
★ByteArrayInputStream 与 ByteArrayOutputStream用于操作字节数组的流对象
ByteArrayInputStream:在构造的时候,需要接受数据源,而且数据源是一个字节数组
ByteArrayOutputStream:在构造的时候,不用定义数据目的,因为该对象中已经内部封装了可变长度的字节数组,这就是数据目的地
因为这两个流对象都操作的数组,并没有使用系统资源,所以不用进行close关闭
源设备:
键盘 System.in 硬盘 FileStream 内存 ArrayStream
目的设备:
控制台 System.out 硬盘 FileStream 内存 ArrayStream
用流的读写来操作数组
★CharArrayReader 与 CharArrayWriter 用于操作字符数组
★StringReader 与 StringWriter
●字符编码
★字符流的出现为了方便操作字符
★更重要的是假如了编码转换
★通过子类转换流来完成
InputStreamReader
OutputStreamWriter
★在两个对象进行构造的时候可以加入字符集
★带字符集的还有
PrintWriter
PrintStream
★编码表的由来
计算机只能识别二进制数据,早期由来是电信号,为了放便应用计算机,让他可以识别各个国家的文字,就将各个国家的文字用数字来表示,并一一对应,形成一张表,这就是编码表
★常见的编码表
▼ASCII:美国标准信息交换码:用一个字节的7位可以表示
▼ISO8859-1:拉丁码表,欧洲码表:用一个字节的8位表示
▼GB2312:中国的中文编码表
▼GBK:中国的中文编码表升级,融合了更多的中文文字字符号
▼Unicode:国际标准码,融合了多种文字:所有文字都使用两个字节来表示,java语言使用的就是unicode
▼UTF-8:最多用三个字节来表示一个字符
public static void main(String[] args) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("g:/utf-8.txt"),"GBK");
InputStreamReader isr = new InputStreamReader(new FileInputStream("g:/utf-8.txt"),"GBK");
osw.write("你好");
osw.close();
}
★编码
字符串变字节数组
★解码
字节数组变字符串
Stringàbyte[]; str.getByte();
str.getBytes(String charsetName)
byte[]àString; new String(byte[]);
String(byte[] bytes, Charset charset)
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "你好";
byte[] bytes = s.getBytes("UTF-8");
System.out.println(Arrays.toString(bytes));
System.out.println(new String(bytes,"UTF-8"));
byte[] bytes1 = s.getBytes("GBK");
System.out.println(Arrays.toString(bytes1));
byte[] bytes2 = s.getBytes("Unicode");
System.out.println(Arrays.toString(bytes2));
byte[] bytes3 = s.getBytes();
System.out.println(Arrays.toString(bytes3));
}
★服务器是iso8859-1
需要先用iso8859-1解码 然后重新编码
不会乱码 原因iso8859-1不支持中文
如果服务器是中文编码集
转来转去就错了
★字符编码-联通
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "联通";
byte[] b = s.getBytes("gbk");
for (byte c : b) {
System.out.println(Integer.toBinaryString(c&255));
}
}
11000001
10101010
11001101
10101000
联通的GBK编码符合UTF-8的格式
联通前加汉字解决