Java File .write()一个整数流

时间:2013-06-15 18:19:26

标签: java file file-io

我运行此代码,我得到“文件写入!”当我打开文件看它时,所写的每件事都没有任何意义。你可以理解我想在文件中写012345678910。是否有任何其他方式可以在文件中写入buffW.write(k);。我犯了其他错误吗?

package thema4_create_write_read_file;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class FW {

    public static void main(String[] args) {
        File newFile = new File("newFile.txt");
        if (newFile.exists()) {
            System.out.println("The file already exists");
        } else {
            try {
                newFile.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                FileWriter fileW = new FileWriter(newFile);
                BufferedWriter buffW = new BufferedWriter(fileW);
                for (int k = 0; k <= 10; k++) {
                    buffW.write(k); // This is where the problem occurs
                }
                buffW.close();
                System.out.print("File written !");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

有没有任何方法可以将(k)写为整数而不是字符串,以便将其读作int呢?

2 个答案:

答案 0 :(得分:4)

Bufferedwriter#write(int c)

  

写一个字符。

     

<强>参数:

     

c - 指定要写入的字符

使用Writer#write(String)

writer.write(String.valueOf(integer));

答案 1 :(得分:1)

BufferedWriter#write(int i)Unicode Table中写出与i对应的字符,您可以使用

查看将要写入的内容
System.out.print((char)k);

现在,如果你想写k的int值,你应该使用PrintWriter

PrintWriter printW = new PrintWriter(fileW);
printW.print(k);

您还可以查看PrintStream#print()方法(System.out是PrintStream的实例),但编写器优先于Streams进行字符I / O操作。

相关问题