TMan
TMan

Reputation: 4122

How to read in a txt file

I'm trying to read in from whats on the first two lines of a txt file, put it on a string and pass that string onto my methods. I'm confused on what I need to do in the main method.

Heres what I have:

    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);

       }

I tried String x = new String(x.getNewFile()) I'm not sure if thats the right way to go with that or not.

Upvotes: 7

Views: 6742

Answers (4)

cV2
cV2

Reputation: 5317

//------------------------------------------------------------------------- //read in local file:

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();
        }

check this :=)

Upvotes: 0

It's even easier in Java 1.5+. Use the Scanner class. Here's an example. Essentially, it boils down to:

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();
    }
  }

...so there's really no reason for you to have a getFileContents() method. Just use Scanner.

Also, the entire program flow could use some restructuring.

  • Don't declare a Stacked inside of your main method. It's likely that's what your testing class should encapsulate.

    Instead, write a private static String method to read the file name from the keyboard, then pass that to to your TestingClass object.

  • Your TestingClass constructor should call a private method that opens that file, and reads in the first 2 (or however many else you end up wanting) lines into private class variables.

  • Afterwards you can instantiate a new Stacked class.

For good encapsulation principles, have your TestClass provide public methods that the Driver program (the class with the public static void main() method can call to access the Stacked instance data without allowing access to the Stacked object directly (hence violating the Law of Demeter).

Likely this advice will seem a little hazy right now, but get in the habit of doing this and in time you'll find yourself writing better programs than your peers.

Upvotes: 3

Justin
Justin

Reputation: 800

Try this:

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

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

Upvotes: 6

Kal
Kal

Reputation: 24910

Reading from a txt file is usually pretty straightforward.

You should use a BufferedReader since you want the first two lines only.

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();

You should change your method signature to return the string. Now, you can say

String x = clas.getFileContent();

Upvotes: 1

Related Questions