import java.io.*; public class Test { //ascii:主要储存英文字符,和数字,标点符号 //utf-8:可以用来存储世界范围主要的语言字符,用1-4个字符 //GBK:用来存储包含中文在内的字符,中文占用2个字节 //iso-8859-1:了解,每个字符占用1个字节,向下兼容ascii public static void main(String[] args) { File file = new File("D:\\123.txt"); FileInputStream fileInputStream = null; InputStreamReader inputStreamReader = null; FileOutputStream fileOutputStream = null; OutputStreamWriter outputStreamWriter = null; String str = null; try { fileOutputStream = new FileOutputStream(new File("D:\\1.txt")); outputStreamWriter = new OutputStreamWriter(fileOutputStream,"ascii"); fileInputStream = new FileInputStream(file); inputStreamReader = new InputStreamReader(fileInputStream,"UTF-16"); char[] chars = new char[1024]; int len; while((len = inputStreamReader.read(chars)) != -1) { outputStreamWriter.write(chars,0,len); str = new String(chars,0,len); } System.out.println(str); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if(inputStreamReader != null) { inputStreamReader.close(); } if(outputStreamWriter != null) { outputStreamWriter.close(); } } catch (IOException e) { throw new RuntimeException(e); } } } //一个char占用2个字节(内存中,内存中的采用unicode字符集),存到文件中取决于编码方式 }
import java.io.*;
public class Test
{
//ascii:主要储存英文字符,和数字,标点符号
//utf-8:可以用来存储世界范围主要的语言字符,用1-4个字符
//GBK:用来存储包含中文在内的字符,中文占用2个字节
//iso-8859-1:了解,每个字符占用1个字节,向下兼容ascii
public static void main(String[] args)
{
File file = new File("D:\\123.txt");
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
FileOutputStream fileOutputStream = null;
OutputStreamWriter outputStreamWriter = null;
String str = null;
try
{
fileOutputStream = new FileOutputStream(new File("D:\\1.txt"));
outputStreamWriter = new OutputStreamWriter(fileOutputStream,"ascii");
fileInputStream = new FileInputStream(file);
inputStreamReader = new InputStreamReader(fileInputStream,"UTF-16");
char[] chars = new char[1024];
int len;
while((len = inputStreamReader.read(chars)) != -1)
{
outputStreamWriter.write(chars,0,len);
str = new String(chars,0,len);
}
System.out.println(str);
}
catch (FileNotFoundException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
finally
{
try
{
if(inputStreamReader != null)
{
inputStreamReader.close();
}
if(outputStreamWriter != null)
{
outputStreamWriter.close();
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
//一个char占用2个字节(内存中,内存中的采用unicode字符集),存到文件中取决于编码方式
}
JAVA使用IO处理流输入输出字符流实现文件内容复制和读取输出-----JAVA
于 2023-07-08 20:10:15 首次发布