Java教程

Java-StringBuffer和StringBuilder

本文主要是介绍Java-StringBuffer和StringBuilder,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package com.example.demo.StringTest;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;

/**
 * @author hanqiang
 * @Classname StringTest
 * @Date 2021/5/20 14:23
 * @Description:
 */
@SpringBootTest
public class StringTest {
    @Test
    public void myTest() throws FileNotFoundException {

        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("aaa1");
        stringBuilder.append(1);
        stringBuilder.append(44.0);
        stringBuilder.append(33.00);
        System.out.println("反转前"+stringBuilder);
        //字符串反转
        stringBuilder.reverse();
        System.out.println("反转后"+stringBuilder);

        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("(这是测试数据");
        stringBuffer.append(11234567);

        try{
            FileReader fileWriter=new FileReader("C:\\Users\\Administrator\\Desktop\\1.txt");
            BufferedReader bufferedReader=new BufferedReader(fileWriter);
            char[] c=new char[20];
            while(bufferedReader.read(c)>0){
                    stringBuffer.append(c);
            }
            FileWriter fileWriter1=new FileWriter("C:\\Users\\Administrator\\Desktop\\2.txt");
            BufferedWriter bufferedWriter=new BufferedWriter(fileWriter1);
            bufferedWriter.write(new String(stringBuffer));
            bufferedWriter.flush();

            bufferedReader.close();
            bufferedWriter.close();

        }catch(Exception e){
            e.printStackTrace();
        }

        stringBuffer.append("------------------结束)");
        stringBuffer.reverse();
        System.out.println("#####3333###############:"+stringBuffer);
        System.out.println();
        //当反转之后,字符串一直处于反转状态,反转回来
        stringBuffer.reverse();
        System.out.println("从第十个字符串开始截取:"+stringBuffer.substring(10));
    }
}

 

这篇关于Java-StringBuffer和StringBuilder的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!