I want to store characters in an array of byte and write this byte array to a file and read the file back and output to the screen

huangapple go评论64阅读模式
英文:

I want to store characters in an array of byte and write this byte array to a file and read the file back and output to the screen

问题

我想将字符存储在字节数组中,并将此字节数组写入文件,然后从文件中读取文件,并输出到屏幕上。

以下是我的代码(我刚刚开始),有人可以帮帮我吗?

public static void main(String[] args) throws IOException
{
   File f = new File("input.txt");
   FileReader fr = new FileReader(f);
   BufferedReader br = new BufferedReader(fr);
   int c = 0;
   while ((c = br.read()) != -1)
   {
      char character = (char) c;
      System.out.println(character);
   }
}
英文:

I want to store characters in an array of byte and write this byte array to a file and read the file back and output to the screen.

Here is my code ( I'm just starting), can anyone help me?

   public static void main(String[] args) throws IOException 
   {
      File f=new File("input.txt");     
      FileReader fr=new FileReader(f);   
      BufferedReader br=new BufferedReader(fr);  
      int c = 0;             
      while((c = br.read()) != -1)         
      {
            char character = (char) c;          
            System.out.println(character);        

答案1

得分: 0

我这里看不到你在哪里将字符数组写入文件input.txt中。
首先,你需要将数据保存到一个文件中,然后再进行读取。

public static void main(String[] args) {
    char[] arr = new char[] {'a', 'b', 'c'};
    byte[] bytes = String.valueOf(arr).getBytes();
    try (BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("input.txt"))) {
        bout.write(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 接下来是你代码的部分
}
英文:

I don't see here Where do you write the character array to the file input.txt?
First you have to save the data to a file and then just read it.

public static void main(String[] args) {
        char [] arr = new char[] {'a', 'b', 'c'};
        byte[] bytes = String.valueOf(arr).getBytes();
        try(BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("input.txt"))) {
            bout.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
       //then part of your code
    }

huangapple
  • 本文由 发表于 2020年9月26日 16:16:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64075411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定