输入输出
Java I/O
文件,内存,键盘(源数据源)----->程序------>文件,内存控制台
java API:java.io;
1.File类:文件的属性和操作
路径:\ //
方法:
创建文件
exists()
creatNewFile()
删除文件
delete()
获取文件相关信息
isfFile
isDirectory()
getName()
getPath()
getAbsolutePath()
length()
package IO;
import java.io.File;
public class FileMethod {
public void creatFile(File file){
if (file.exists()){
file.delete();
try {
file.createNewFile();
}catch (Exception e){
e.printStackTrace();
}
}else {
try {
file.createNewFile();
}catch (Exception e){
e.printStackTrace();
}
}
}
public void showInfo(File file){
if (file.isFile()){
System.out.println(file.getName());
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
System.out.println(file.length());
}else if (file.isDirectory()){
System.out.println("这是个目录");
}
}
public void dele(File file){
file.delete();
System.out.println("删除成功");
}
public static void main(String[] args) {
File file=new File("D:\\hello.txt");
FileMethod fileMethod=new FileMethod();
fileMethod.creatFile(file);
fileMethod.showInfo(file);
fileMethod.dele(file);
}
}
流
各个流的使用
1.字节流-输入流
public abstract class InputStream
int read();从输入流中读取下一个字节,返回0-255之间的int值,返回值代表读出来字节对应的整型数字,读取后会自动往下读到末尾int值为-1
int read(byte[]b):从输入流读取一堆的字节,把这些字节放在字节数组b中。返回值代表的是读到字节的个数(b的长度)
int read(byte[],int off,int len);从输入流读取一堆的字节,把这些字节放在字节数组b中(将第一个字节放在b[off]里).off对应的是b开始存储字节的标识和下表,len代表b数组的长度
close()关闭输入流
2.字节流-输出流
public abstract class OutputStream
package IO;
import java.io.*;
public class Practice {
public byte[] read(File file) {
byte[] b = new byte[(int)file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
try {
fileInputStream.read(b);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return b;
}
public void write(byte[] a, File file) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
try {
fileOutputStream.write(a, 0, a.length);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Practice practice = new Practice();
File file = new File("D:\\我的青春我做主.txt");
byte a[]= practice.read(file);
File file1 = new File("D:\\java summer study\\我的青春我做主.txt");
practice.write(a,file1);
}
}
遇到的问题
UTF-8编码中一个中文占三个字节