Java通过FileWriter的write方法写i…

本文详细解读了Java代码片段,重点分析了如何通过文件读取、字符转换为数值以及数据写入的过程。代码展示了将文本文件中的数字字符序列转换为整数并写入到另一个文件中,同时讨论了错误处理机制和潜在优化点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.*;

public class sum {
    public static void Sum(String s1,String s2,String s3){
        try{
            int num=0,temp=0,ch;
            FileWriter w = new FileWriter(s2, true);
            FileReader r = new FileReader(s1);
            while((ch=r.read())!=-1){
                switch((char)ch){
                    case '1':temp = temp*10+1;break;
                    case '2':temp = temp*10+2;break;
                    case '3':temp = temp*10+3;break;
                    case '4':temp = temp*10+4;break;
                    case '5':temp = temp*10+5;break;
                    case '6':temp = temp*10+6;break;
                    case '7':temp = temp*10+7;break;
                    case '8':temp = temp*10+8;break;
                    case '9':temp = temp*10+9;break;
                    case '0':temp = temp*10+0;break;
                    default:{
                        num+=temp;
                        temp = 0;
                        break;
                        }
                }
            }
            //System.out.println(num);
            w.write(s3);
            w.write(num);//问题就出在这里
            w.close();
            }catch (Exception e){
                e.printStackTrace();
                }
    }
    public static void main(String[] args){
        String read_path_import = "import.txt";
        String read_path_comment = "comment.txt";
        String read_path_like = "like.txt";
        String write_path = "sum.txt";
        String tips_import = ":";
        String tips_comment = ":";
        String tips_like = ":";
        Sum(read_path_import,write_path,tips_import);
        Sum(read_path_comment,write_path,tips_comment);
        Sum(read_path_like,write_path,tips_like);
        }
}

原因出在这里:

FileWriter从类OutputStreamWriter继承的
1、public void write(int c)
           throws IOException       写入单个字符。
c - 指定要写入字符的ASCII。

这里data数组中的整数是作为字符的ASCII,最终显示的是ASCII值为这些的字符,并不是这些数字本身。要显示这些数字本身,可改为:

fos.write(String.valueOf(data[i])); 

注意valueOf()方法的大小写。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值