String类、输出和输入处理上

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();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值