如何读取txt文件

7

我想读取txt文件前两行的内容,将其存入字符串中并将该字符串传递给我的方法。我不确定在主函数中需要做什么。

以下是我的代码:

    public class TestingClass  {
Stacked s;// = new Stacked(100);
 String Finame;

public TestingClass(Stacked stack) {
    //Stacked s = new Stacked(100);
    s = stack;
    getFileName();
    readFileContents(); 
}

public void readFileContents() {
    boolean looping;
    DataInputStream in;
    String line = "" ;
    int j, len;
    char ch;

    try {
        in = new DataInputStream(new FileInputStream(Finame));
        len = line.length();
        for(j = 0; j<len; j++) {
                System.out.println("line["+j+"] = "+line.charAt(j));
        }
    } 

    catch(IOException e) {
            System.out.println("error " + e);
    }
}   

public void getFileName() {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter File Name");
    Finame = in.nextLine();
    System.out.println("You Entered " + Finame);
}

       public static void main(String[] args) {
         Stacked st = new Stacked(100);
         TestingClass clas = new TestingClass(st);
         //String y = new String("(z * j)/(b * 8) ^2");
         // clas.test(y);

       }

我尝试了以下代码:String x = new String(x.getNewFile()),但我不确定这是否是正确的方法。

4个回答

6

试试这个:

File file = new File("file.txt");

BufferedReader reader = new BufferedReader(new FileReader(file));
String line1 = reader.readLine();
String line2 = reader.readLine();

我应该加上 try catch 吗? - TMan
你可以使用try/catch块来捕获I/O异常。或者你的方法可以抛出该异常。 - Justin
当我运行它时,我没有得到任何输出。为了测试它,我将line1传递给一个方法clas.test(line1)...没有得到任何输出。 - TMan
你能找到并打开这个文件吗? - Justin
我只是在Eclipse中创建了一个txt文件。它可以用于我的其中一种方法,但不适用于我尝试的第一个方法。谢谢帮助。 - TMan

3

在Java 1.5+中,这更加容易。使用Scanner类。以下是一个示例。本质上,它可以归结为:

import java.io.*;
import java.util.Scanner;
public static void main(String... aArgs) throws FileNotFoundException {
    String fileName = "MYFILE HERE";
    String line = "";
    Scanner scanner = new Scanner(new FileReader(fileName));
    try {
      //first use a Scanner to get each line
      while ( scanner.hasNextLine() ){
        line = scanner.nextLine();
      }
    }
    finally {
      //ensure the underlying stream is always closed
      //this only has any effect if the item passed to the Scanner
      //constructor implements Closeable (which it does in this case).
      scanner.close();
    }
  }

所以你没有理由拥有一个getFileContents()方法。只需使用Scanner即可。

此外,整个程序流程需要重新构建。

  • 不要在main方法中声明Stacked。很可能这是你的测试类应该封装的内容。

    相反,编写一个私有静态字符串方法从键盘读取文件名,然后将其传递给TestingClass对象。

  • 您的TestingClass构造函数应该调用一个私有方法来打开该文件,并将前2行(或您最终希望的任何其他行)读入私有类变量中。

  • 之后,您可以实例化一个新的Stacked类。

为了良好的封装原则,让您的TestClass提供公共方法,以便Driver程序(具有public static void main()方法的类)可以调用这些方法来访问Stacked实例数据,而不允许直接访问Stacked对象(从而违反Demeter法则)。

很可能现在这个建议看起来有点模糊,但养成这个习惯,时间久了你会发现自己写的程序比同龄人更好。

换句话说,您使用Scanner接口从控制台读取数据(System.in是InputStream)。您可以以同样的方式使用相同的接口从文件中读取。 - Visionary Software Solutions

1

从txt文件读取通常很简单。

因为您只想要前两行,所以应该使用BufferedReader。

FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
linecount = 0;
StringBuilder myline = new StringBuilder();
String line = "";

while ( (linecount < 2) && ((line = br.readLine()) != null) ) {
     myline.append(line);
     linecount++;
}

// now you have two lines in myline. close readers/streams etc
return myline.toString();

你应该更改方法签名以返回字符串。现在,你可以这样说:
String x = clas.getFileContent();

0

//------------------------------------------------------------------------- //读取本地文件:

String content = "";
        try {
            BufferedReader reader = new BufferedReader(new FileReader(mVideoXmlPath));
            do {
                String line;

                line = reader.readLine();

                if (line == null) {
                    break;
                }
                content += line;
            }
            while (true);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

检查一下 :=)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接