在以下程序中,我从控制台获取输入并将奇数个字符甚至多个字符存储在单独的文件中。但是当我运行程序时,我只得到一个字符。
例如,如果我将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()));
}
}
答案 0 :(得分:2)
试试这个:首先写入文件,然后关闭文件,然后打开新文件:
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);
}