【问题标题】:Can't write number with FileWriter [duplicate]无法用 FileWriter 写入数字 [重复]
【发布时间】:2018-03-06 18:12:42
【问题描述】:

这是我的代码,我希望将 b[i] 写入文件名 test.txt,但它不起作用。它只是写一些符号之类的东西。感谢您的帮助。

public class btl {
public static boolean IsPrime(int n) {

    if (n < 2) {
        return false;
    }

    int squareRoot = (int) Math.sqrt(n);
    for (int i = 2; i <= squareRoot; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}




public static void main(String args[]) {
    Scanner scanIn = new Scanner(System.in);
    int first = 0;
    int second = 0;
    try {
        System.out.println("Input First Number");
     first = scanIn.nextInt();
        System.out.println("Input Second Number");
        second= scanIn.nextInt();
    }
    catch(Exception e) {
        System.out.println("Something wrong!");
    }
    int x = first;
    int y = second;
    int a;
    int[] b = new int[y];

    Thread threadA = new Thread(new Runnable() {
        @Override
        public void run() {     
            int c=0;
            for(int i=x; i<y; i++) {   
                if(IsPrime(i)) {
                    b[c] = i;
                    System.out.println(b[c]);
                    c++;
               }
         }


        }
    });
    threadA.start();


    try(FileWriter fw = new FileWriter("test.txt")){

            for(int i =0; i<y; i++)
            {
             fw.write(b[i]);
            }
        }
    catch(IOException exc) {
        System.out.println("EROR! " + exc);
    }

}

}

This is my display console

And this is file "test.txt"

我不知道为什么 FileWriter 在文件 text.txt 中写入符号。我想要它的数组 b[i] 的数量。

【问题讨论】:

  • 看起来您正在将数字写入 test.txt。它们是十六进制的,而不是字符串。如果需要文本,将其转换为字符串,然后输出字符串。

标签: java arrays filewriter


【解决方案1】:

FileWriter.write(int) 写入一个单个字符。 你可能想要FileWriter.write(String)如:

    fw.write(Integer.toString(b[i]));

【讨论】:

    猜你喜欢
    • 2020-08-28
    • 2020-07-15
    • 2013-07-19
    • 1970-01-01
    • 2014-03-13
    • 2013-03-23
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    相关资源
    最近更新 更多