文件2.txt内的字符为"你好,今天天气不错!" 
我用readUTF读取不到任何字符,是不是一定要写入的时候用writeUTF才能用readUTF读取到相应的字符?求一个答案import java.io.*;
public class DataInput
{
public static void main(String[] args) throws Exception
{
File f=new File("d:\\hahajava\\2.txt");
FileInputStream fis=new FileInputStream(f);
DataInputStream dis=new DataInputStream(fis);
try
{
System.out.println(dis.readUTF());
dis.close();
        }
    catch(Exception e){}
}
}

解决方案 »

  1.   

    为何用DataInputStream?
    那个是读字符用的你读文本文件的话,用读取字节的流
    用BufferedReader读就是了
      

  2.   

    static String  readUTF(DataInput in) Reads from the stream in a representation of a Unicode character string encoded in Java modified UTF-8 format; this string of characters is then returned as a String.这是API上对此方法的解释...如果你文本里是修改过的UTF-8格式的话...就可以读出来...否则是读不出来的...如果你用的是中文系统的话...TXT文件默认的编码应该不是这个.
      

  3.   

    2楼说的很好...的确用BufferedReader比较好...readLine()方法...读一行..多爽啊...
      

  4.   

    用BufferedReader类读取字符
    public static void main(String[] args) {
            BufferedReader reader = null;
           
            try {
                File file = new File("D:/xx.txt"); // Your txt file's path
                reader = new BufferedReader(new FileReader(file));
                String line = null;
               
                while ((line = reader.readLine()) != null) {
                    // Removing the extra blank spaces.
                    // Operating the modified line.
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e2) {
                    }
                }
            }
    }
      

  5.   

    一定要写入的时候用writeUTF才能用readUTF读取到相应的字符
    楼主已经知道了答案 要是用DataInputStream和DataOutputStream读写字符串就只能这样用