如何读取txt文件

时间:2011-09-17 22:34:01

标签: java

我正在尝试从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 个答案:

答案 0 :(得分:6)

试试这个:

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

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

答案 1 :(得分:3)

在Java 1.5+中更容易。使用Scanner课程。这是一个example。从本质上讲,它归结为:

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()方法。只需使用扫描仪。

此外,整个计划流程可能会使用一些重组。

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

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

  • 您的TestingClass构造函数应该调用一个打开的私有方法 该文件,并在前两个读取(或者你最终的其他许多 想要)线到私人类变量。

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

对于良好的封装原则,请让您的TestClass提供公共方法,使得Driver程序(具有 public static void main()方法的类可以调用以访问Stacked实例数据,不允许直接访问Stacked对象(因此违反了Law of Demeter)。

可能这个建议现在看起来有点朦胧,但养成这样做的习惯,及时你会发现自己编写的程序比同龄人更好。

答案 2 :(得分: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();

答案 3 :(得分: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();
        }

检查一下:=)

相关问题