花几千上万学习Java,真没必要!(三十八)

 

 

 

 

 

测试代码1:

package iotest.com;
import java.nio.charset.StandardCharsets;  
import java.io.UnsupportedEncodingException;  
  
public class StringByteConversion {  
  
    public static void main(String[] args) throws UnsupportedEncodingException {  
        // 原始字符串  
        String originalString = "Hello, 世界!";  
  
        byte[] defaultBytes = originalString.getBytes();  
		String defaultDecodedString = new String(defaultBytes);  
		System.out.println("默认字符集编码后解码: " + defaultDecodedString);  
  
        // 使用指定的字符集(UTF-8)编码字符串  
        byte[] utf8Bytes = originalString.getBytes(StandardCharsets.UTF_8.name());  
        String utf8DecodedString = new String(utf8Bytes, StandardCharsets.UTF_8.name());  
        System.out.println("UTF-8编码后解码: " + utf8DecodedString);  
  
        // 尝试使用ISO-8859-1(不支持中文)编码和解码字符串,以展示可能的乱码  
        try {  
            byte[] isoBytes = originalString.getBytes("ISO-8859-1");  
            String isoDecodedString = new String(isoBytes, "ISO-8859-1");  
            System.out.println("ISO-8859-1编码后解码(可能导致乱码): " + isoDecodedString);  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  

    }  
}

运行结果如下:

 

 

测试代码2:

package iotest.com;
import java.io.ByteArrayInputStream;  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;   
import java.io.OutputStreamWriter;  
  
public class StreamMergerExample {  
    public static void main(String[] args) {  
        try {  
            // 创建一个ByteArrayOutputStream捕获写入的字节  
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();  
  
            // 使用UTF-8字符编码创建OutputStreamWriter  
            OutputStreamWriter writer = new OutputStreamWriter(byteStream, "UTF-8");  
  
            // 写入文本  
            writer.write("Hello, 世界!");  
  
            // 刷新OutputStreamWriter,确保所有内容都被写入到底层ByteArrayOutputStream  
            writer.flush();  
  
            // 关闭OutputStreamWriter
            // writer.close(); // 如果不打算重用byteStream,可以调用close()  
  
            // 读取需要将其转换为ByteArrayInputStream  
            InputStream inputStream = new ByteArrayInputStream(byteStream.toByteArray());  
  
            // 使用UTF-8字符编码(与写入时相同)创建InputStreamReader  
            InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");  
  
            // 可以用BufferedReader读取  
            int c;  
            while ((c = reader.read()) != -1) {  
                // 打印int的字符表示  
                if (c >= 0 && c <= 0xFFFF) { // 有效性检查(Java中的char是16位的)  
                    System.out.print((char) c);  
                }  
            }  
  
           //如果使用的是包装流的类(如BufferedReader),则应该关闭。  
  
            System.out.println("\n读取完成。");  
  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

运行结果如下:

 

测试代码3:

package iotest.com;
import java.io.BufferedWriter;  
import java.io.FileWriter;  
import java.io.IOException;  
public class WriterExample {
    public static void main(String[] args) {
        try {
            // 创建一个BufferedWriter对象写入文件
            BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));

            // 写一个字符
            writer.write('A');
            
            // 写入一个字符数组
            char[] charArray = {'B', 'C', 'D'};
            writer.write(charArray);

            // 写入字符数组的一部分
            writer.write(charArray, 1, 2);

            // 刷新流
            writer.flush();

            // 关闭流
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

测试代码4:

package iotest.com;
import java.io.BufferedReader;  
import java.io.BufferedWriter;   
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.OutputStreamWriter;  
  
public class FileReadWriteUTF8Example {  
    public static void main(String[] args) {  
        // 指定文件路径  
        String filePath = "E:\\Test\\a.txt";  
  
        // 写入文件,使用UTF-8编码  
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"))) {  
            String content = "这是一段测试文本,使用UTF-8编码写入。默认使用平台的默认字符编码。如果需要在不同平台间共享文件,或者文件包含特殊字符(如中文),使用显式的字符编码,如UTF-8。";  
            writer.write(content);  
            System.out.println("写入成功。");  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
        // 读取文件,使用UTF-8编码,并打印到控制台  
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"))) {  
            String line;  
            while ((line = reader.readLine()) != null) {  
                System.out.println(line);  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

运行结果如下:

 

测试代码5:

package iotest.com;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderTest {  
    public static void main(String[] args) {  
        try {  
            // 创建一个FileReader对象读取文件  
            FileReader reader = new FileReader("E:\\Test\\a.txt");  
              
            // 使用read方法一次读取一个字符数据  
            int charData;  
            while ((charData = reader.read()) != -1) {  
                System.out.print((char) charData); // 打印读取的字符  
            }  
            System.out.println(); //方法换行  
  
            // 使用read一次读取一个字符数组数据  
            char[] charArray = new char[3];  
            int numCharsRead;  
            
            //使用read方法逐个读取字符并打印出来,直到文件末尾(-1)。
            while ((numCharsRead = reader.read(charArray)) != -1) {  
                // 只打印实际读取的字符数  
                for (int i = 0; i < numCharsRead; i++) {  
                    System.out.print(charArray[i]);  
                }  
            }  
  
            // 关闭流  
            reader.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

测试代码6:Copy文本。

package iotest.com;
import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
  //readLine()方法读取一行文本。
  //它读取字符直到遇到换行符(\n)、回车符(\r)、回车后紧跟换行符(\r\n)或到达文件末尾。
  //返回包含该行内容的字符串,但不包括任何行终止符。
  //如果已到达流的末尾且没有更多的行可供读取,则返回null。
  //readLine()为按行读取文本文件内容的理想选择。
public class FileCopyTest {  
    public static void main(String[] args) {  
        String sourceFile = "E:\\Test\\a.txt";  
        String destFile = "D:\\AA\\destination.txt";  
  
        BufferedReader br = null;  
        BufferedWriter bw = null;  
  
        try {  
            br = new BufferedReader(new FileReader(sourceFile));  
            bw = new BufferedWriter(new FileWriter(destFile));  
  
            String line;  
            //readLine()按行读取源文件的内容
            while ((line = br.readLine()) != null) {  
                bw.write(line);  
                bw.newLine(); // 写入行分隔符  
            }  
  
            System.out.println("文件复制成功!");  
  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("文件复制失败!");  
        } finally {  
            try {  
                if (br != null) {  
                    br.close();  
                }  
                if (bw != null) {  
                    bw.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}

测试代码7:字符缓冲流复制文件

package iotest.com;
import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
public class FileCopyExample {  
    public static void main(String[] args) {  
        String sourceFile = "D:\\AA\\a.txt";  
        String destFile = "E:\\Test\\a.txt";  
  
        // 确保目标目录存在
  
        FileReader fileReader = null;  
        FileWriter fileWriter = null;  
  
        try {  
            fileReader = new FileReader(sourceFile);  
            fileWriter = new FileWriter(destFile);  
  
            char[] buffer = new char[1024]; // 使用一个缓冲区存储读取的字符  
            int numCharsRead;  
  
            // 循环读取文件直到到达末尾  
            while ((numCharsRead = fileReader.read(buffer)) != -1) {  
                // 写入实际读取的字符数到目标文件  
                fileWriter.write(buffer, 0, numCharsRead);  
            }  
  
            System.out.println("文件复制成功!");  
  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("文件复制失败!");  
        } finally {  
            // 关闭资源  
            try {  
                if (fileReader != null) {  
                    fileReader.close();  
                }  
                if (fileWriter != null) {  
                    fileWriter.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值