英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论