java中读取文件字节数组,怎么能以UTF-8格式读取

时间:2023-01-11 10:21:48
java中读取文件字节数组,怎么能以UTF-8格式读取

public static byte[] getBytesFromFile(String fileName) {
     //fileName="C:/Users/ZPTian/Desktop/WebServicetest.txt";
     File f = new File(fileName);
        if (f == null) { 
            return null; 
        } 
        try { 
            FileInputStream stream = new FileInputStream(f); 
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000); 
            byte[] b = new byte[1000]; 
            int n; 
            while ((n = stream.read(b)) != -1) 
                out.write(b, 0, n); 
            stream.close(); 
            out.close(); 
            
            return out.toByteArray(); 
        } catch (IOException e) { 
        } 
        return null; 
    } 

返回的都是116,101,115,116,102,97,120,-50,-46,-75,-60,-76,-85,-43,-26
中文的都带-号,怎么以UTF-8读取呢

6 个解决方案

#1


字节素没有编码概念地,转换成字符才有,
比如用reader啥的

#2


LZ是刚刚开始学JAVA的吗?最好看看API文档,哪里有详细介绍!

#3


getBytesFromFile

#4



//写
new BufferedWriter(new OutputStreamWriter(new ByteArrayOutputStream(),"UTF-8"));

//读
new BufferedReader(new InputStreamReader(new FileInputStream(""),"UTF-8"));

#5


引用 4 楼 zhangyy130 的回复:
Java code//写new BufferedWriter(new OutputStreamWriter(new ByteArrayOutputStream(),"UTF-8"));//读new BufferedReader(new InputStreamReader(new FileInputStream(""),"UTF-8"));


更全的~~~

//写
BufferedWriter w= new BufferedWriter(new OutputStreamWriter(new ByteArrayOutputStream(),"UTF-8"));

//读
BufferedReader r=new BufferedReader(new InputStreamReader(new FileInputStream(""),"UTF-8"));

String temp=null;
while((temp=r.readLine())!=null){
w.write(temp);
w.write("\r\n");
}

#6


恩,不错,但是有一点,就是上传一下帮助文档,为什么读不出来啊

#1


字节素没有编码概念地,转换成字符才有,
比如用reader啥的

#2


LZ是刚刚开始学JAVA的吗?最好看看API文档,哪里有详细介绍!

#3


getBytesFromFile

#4



//写
new BufferedWriter(new OutputStreamWriter(new ByteArrayOutputStream(),"UTF-8"));

//读
new BufferedReader(new InputStreamReader(new FileInputStream(""),"UTF-8"));

#5


引用 4 楼 zhangyy130 的回复:
Java code//写new BufferedWriter(new OutputStreamWriter(new ByteArrayOutputStream(),"UTF-8"));//读new BufferedReader(new InputStreamReader(new FileInputStream(""),"UTF-8"));


更全的~~~

//写
BufferedWriter w= new BufferedWriter(new OutputStreamWriter(new ByteArrayOutputStream(),"UTF-8"));

//读
BufferedReader r=new BufferedReader(new InputStreamReader(new FileInputStream(""),"UTF-8"));

String temp=null;
while((temp=r.readLine())!=null){
w.write(temp);
w.write("\r\n");
}

#6


恩,不错,但是有一点,就是上传一下帮助文档,为什么读不出来啊