Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 有人能解释一下为什么这个代码没有在我的txt文件中输入数字吗_Java - Fatal编程技术网

Java 有人能解释一下为什么这个代码没有在我的txt文件中输入数字吗

Java 有人能解释一下为什么这个代码没有在我的txt文件中输入数字吗,java,Java,我想让这个程序在我的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 c

我想让这个程序在我的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) {

    }






   }
   }
ByteBuffer bff=ByteBuffer.allocate(100);
FileChannel ch=st.getChannel();
IntBuffer ib=bff.asIntBuffer();
for(int i=0;i
添加以下代码

finally{
 st.close();
 }

您可以在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) {
   ...
}

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


请看一下以字节形式写入整数的示例,但要将它们正确显示为ascii字符串,请将
IntBuffer
更改为
CharBuffer

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

完成写入后,请关闭
st
。建议首先使用try-with-resources,但如果我可以随时将数字转换为字符串并将其放入CharBuffer中,为什么要使用IntBuffer?
    finally {
        outputStream.flush();
        outputStream.close();
    }