【问题标题】:Can someone explain me why this code doesnt put numbers in my txt file有人能解释一下为什么这段代码没有在我的 txt 文件中输入数字吗
【发布时间】:2018-01-19 20:01:26
【问题描述】:

我希望这个程序在我的 txt 文件中写入数字,但它写了一些奇怪的符号。有没有人可以修复它并让它从数组中写入数字

package int1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;

public class broj_u_skl {
public static void main(String[] args) {
    File a = new File("C:\\Users\\Jovan\\Desktop");
    File b = new File(a,"Pisem.txt");
    try {
    b.createNewFile();
}catch(Exception e) {

}
    FileOutputStream st = null;
    try {
        st = new FileOutputStream(b);
    }catch(Exception e) {

    }

这是那个数组:

    int[] c = {1,2,3,4,5,6,7,8,9};

但上面没有写这个数字。

    ByteBuffer bff = ByteBuffer.allocate(100);
    FileChannel ch = st.getChannel();
    IntBuffer ib = bff.asIntBuffer();
    for (int i = 0; i < c.length; i++) {
        ib.put(c[i]);

    }
    bff.position(4*ib.position());
    bff.flip();
    try {
        ch.write(bff);
    }catch(IOException e) {

    }






   }
   }

【问题讨论】:

  • 写完后关闭st

标签: java


【解决方案1】:

您将整数写入字节,但要将它们正确显示为 ascii 字符串,请将您的 IntBuffer 更改为 CharBuffer

    CharBuffer charBuffer = byteBuffer.asCharBuffer();
        for (int i = 0; i < c.length; i++) {
            charBuffer.put("" + c[i]);
        }

别忘了刷新并关闭您的 FileOutputStream:

    finally {
        outputStream.flush();
        outputStream.close();
    }

【讨论】:

  • 但是当我可以随时将数字转换为字符串并将其放入 CharBuffer 时,我为什么还要使用 IntBuffer?
【解决方案2】:

你可以在 finally 子句中关闭 st

FileOutputStream st = null;
try {
    st = new FileOutputStream(b);
    ...
} catch(Exception e) {
    ...
} finally {
    st.close();
}

或者更好的解决方案是使用 try-with-resources 子句,它将为您关闭 st。

try (FileOutputStream st = new FileOutputStream(b)) {
   ...
} catch(Exception e) {
   ...
}

【讨论】:

  • try-with-resources 应该是第一个推荐的东西
【解决方案3】:

这样做是将整数作为字节写入文件,而不是 ascii 字符串。

看看how to write an array to a file Java的例子

【讨论】:

    【解决方案4】:

    添加以下代码

    finally{
     st.close();
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      相关资源
      最近更新 更多