请教各位大侠,怎么读取D:\test.txt文件内容,并打印到控制台.
读取ini文件与txt文件相同吗?

解决方案 »

  1.   

    1. BufferedReader in = new BufferedReader(new FileReader("D:\\test.txt"));
    String s, s2 = new String();
    while((s = in.readLine()) != null)
    s2 += s + "\n";
    in.close();
                      System.out.println(s2);
    2. 应该是一样的, 可以试试.
      

  2.   

    BufferedReader br = null;
        FileReader fr = null;
        try {
          fr = new FileReader("d:\\test.txt");
          br = new BufferedReader(fr);
          
          String str = null;
          StringBuffer sb = new StringBuffer();
          while ((str = br.readLine()) != null) {
            sb.append(str + "\n");
          }
          System.out.println(sb.toString());
        } catch (Exception ex) {
          System.out.println(ex.toString());
        } finally {
        }
      

  3.   

    import java.io.*;
    FileReader f = new FileReader("c:\\MYP.dat");
    BufferedReader br = new BufferedReader(f);
    String str;
    while((str=br.readLine())!=null) {
    System.out.print(str);
    }
    br.close();
    f.close();
      

  4.   

    读取ini和txt是一样的。
    redline()是整行读取,如果只读取字符,可以用FileReader的read()方法。
      

  5.   

    非常感谢!!
    可是我执行下面程序时为什么会报错呢?
    public class B
    {
    BufferedReader  in  =  new  BufferedReader(new  FileReader(  "D:\\test.txt  "));  
                           String  s,s2  =  new  String(); 
                           while((s  =  in.readLine())  !=  null)
                              s2  +=  s+"\n"; 
                           in.close();  
                           
       public static void main(String args[])
       {
        B b = new B();
        System.out.println(s2); 
       } 
    }
      

  6.   

    import java.io.*;public class B
    {

    public String readfile() throws IOException{
    BufferedReader  in  =  new  BufferedReader(new  FileReader(  "D:\\test.txt  "));  
                           String  s,s2  =  new  String(); 
                           while((s  =  in.readLine())  !=  null)
                              s2  +=  s+"\n"; 
                           in.close();  
                           return s2;
    }
       public static void main(String args[])
       {
        B b = new B();
        try {
    System.out.println(b.readfile());
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

       } 
    }
      

  7.   

    s2是class B里的一个字段,不能直接调用。System.out.print(b.s2);                       
      

  8.   

    import java.io.*;
    class read
    {
    public static void main(String[] args)
    {
    int i;
    try
    {
    FileInputStream in = new FileInputStream("D:\\test.txt");
    while((i=in.read())!=-1)
    {
    System.out.print((char)i);
    }
    in.close();
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
    }

    }
    不过如果文件中有汉字的话会是乱码