输入和输出处理(上)
String类
- String:
是final类型,不可被继承,底层是char类型数组常量,不可更改
而对String对象重新赋值的过程,其实是新建对象的过程
如果需要对String对象频繁赋值,则不推荐使用String
线程安全:Synchronized 保证线程间隔离 - String:不可被改变,真正意义上的安全,
在频繁字符串拼接的情况下,速度非常慢 - StringBuffer:线程安全,速度慢
- StringBuilder:线程不安全,速度快
Java I/O
文件
- 什么是文件?
相关记录或放在一起的数据的集合 - Java程序如何访问文件属性?
JAVA API :java.io.File 类 - File类访问文件属性
File file = new File( String pathname );
File类常用用法
流
通过流来读写文件,流是一组有序的数据序列,以先进先出方式发送信息的通道
输入/输出流与数据源
Java流的分类
FileInputStream
- InputStream类常用方法
int read( )
int read(byte[] b)
int read(byte[] b,int off,int len)
void close( )
int available():可以从输入流中读取的字节数目 - 子类FileInputStream常用的构造方法
FileInputStream(File file)
FileInputStream(String name)
public static String readFile(String path){
FileInputStream fis = null;
String str = null;
try {
fis = new FileInputStream(path);
byte[] b = new byte[fis.available()];
fis.read(b);
str = new String(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return str;
}
FileOutputStream
- OutputStream类常用方法
void write(int c)
void write(byte[] buf)
void write(byte[] b,int off,int len)
void close()
void flush():强制把缓冲区的数据写到输出流中 - 子类FileOutputStream常用的构造方法
FileOutputStream (File file)
FileOutputStream(String name)
FileOutputStream(String name,boolean append)
//这里path路径必要包含有文件夹路径,否则.getParentFile()会报错
public static void writeFile(String str, String path, boolean isAppend){
File f =new File(path);
if (!f.getParentFile().exists()){
f.getParentFile().mkdirs();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f, isAppend);
byte[] b = str.getBytes();
fos.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}