Adz
Adz

Reputation: 2847

Copying the first line of a text file?

    for (int i = 0; i<file.length(); i++) { 
         while (line.charAt(i) != '\n') { 
          first = file.substring(0,i); 
        }
    } 

I'm trying to get the code above to increment through the text, and if it finds a breakline, add that line to the instance variable first. I'm getting an out of bounds error for some reason.

I'm reading a text file using BufferedReader. I want to add the first line of the text file to an instance variable called line, and then pass it to a FileWriter which writes it into a new text file.

Also, another problem I have is, if I write the file to the new file, it adds it x amount of times (that the writer is called). How can I make it so it only writes this line only once?

Thank you.

EDIT: The current FileWriter I'm using is writing multiple new lines to the new file. Say I add the line variable writer.write(line); it'll write

line
1
line
2
line
3

I want it like this:
line
1
2
3

static void file(String in) {
//nums is instance variable
String numbers = nums;
        try {
            FileWriter writer = new FileWriter(output,true);
            writer.write(line + System.getProperty("line.separator", "\r\n"));
            writer.write(numbers + System.getProperty("line.separator", "\r\n"));
            writer.close();
        }   catch(IOException ex) {
            ex.printStackTrace();
        }
}

Upvotes: 0

Views: 904

Answers (3)

gkrls
gkrls

Reputation: 2664

You can use Scanner. Something like that should do

Scanner in = new Scanner(new File("text.txt"))
line = in.nextLine();

The in.nextLine() reads up to \n and returns a string. If you want more lines you can use it in a while loop:

while(in.hasNextLine())
    line = in.nextLine();

etc..

Upvotes: 1

toidiu
toidiu

Reputation: 965

An explanation would be nice as pointed out by redFIVE. I am opening the file as an input stream and then reading all of its contents into a BufferReader (http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html). The BufferReader supports the function readline() which will handle all the messy hard work and let you access the file line by line. Lastly close the buffer to release and system resources.

private void readFile(File file) throws IOException {
    FileInputStream fis = new FileInputStream(file);

    //Construct BufferedReader from InputStreamReader
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));

    String line = null;
    while ((line = br.readLine()) != null) {
       //do something with line
    }

    br.close();
}

Upvotes: 1

radar
radar

Reputation: 605

If you're using a BufferedReader, just using readLine() works much more easily.

String line = br.readLine();

I'm not exactly sure what the second part of your question is asking. Can you clarify what the problem/usage is?

Upvotes: 1

Related Questions