gpt4 book ai didi

java - 从文件读取时出错

转载 作者:行者123 更新时间:2023-12-02 06:27:08 25 4
gpt4 key购买 nike

在下面的程序中,我从控制台获取输入并将奇数个字符和偶数个字符存储在单独的文件中。但是当我运行该程序时,我只得到一个字符。

例如,如果我将 Hello 作为输入,并且从偶数文件中读取,则它仅显示“o”。

import java.io.*;
import java.util.*;

class OddEvenFile
{
public static void main(String args[])throws IOException
{
char tmp;
String str;
StringBuffer rese=new StringBuffer();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
FileInputStream fine=new FileInputStream("C:\\Users\\Siva\\Documents\\Java\\Even.txt");
FileInputStream fino=new FileInputStream("C:\\Users\\Siva\\Documents\\Java\\Odd.txt");
FileOutputStream foute=new FileOutputStream("C:\\Users\\Siva\\Documents\\Java\\Even.txt");
FileOutputStream fouto=new FileOutputStream("C:\\Users\\Siva\\Documents\\Java\\Odd.txt");
System.out.print("\nEnter a String :");
str=br.readLine();
System.out.print("\n Length :"+str.length());
for(int i=1;i<str.length();i++)
{

char c=str.charAt(i);
if(i%2 == 0)
foute.write(c);
else
fouto.write(c);
}
while(fine.read()!=-1)
{
tmp=(char)fine.read();
//tmp=String.valueOf()
rese.append(tmp);
}
System.out.print("In even file :"+(rese.toString()));
}
}

最佳答案

试试这个:首先写入文件,然后关闭文件,然后打开新文件:

public static void main(String args[])throws IOException
{
char tmp;
String str;
StringBuffer rese=new StringBuffer();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
FileOutputStream foute=new FileOutputStream("Even.txt");
FileOutputStream fouto=new FileOutputStream("Odd.txt");
System.out.print("\nEnter a String :");
str=br.readLine();
System.out.print("\n Length : "+str.length() + "\n");

for(int i = 0;i < str.length(); i++)
{
char c=str.charAt(i);
if(i%2 == 0)
foute.write(c);
else
fouto.write(c);
}

foute.close();
fouto.close();

FileInputStream fine=new FileInputStream("Even.txt");
FileInputStream fino=new FileInputStream("Odd.txt");

String s = "";
while(fine.available() > 0)
{
s += (char) fine.read();
}

fine.close();
fino.close();
System.out.print("In even file : " + s);
}

关于java - 从文件读取时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20415635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com