How to Read 1st line of a file with BufferedReader? - java

I was experimenting with BufferedReader to read 1st line file to a string. How do I do this? Also how can I read an entire file to a string? How to read a particular line like readline(int line) without iterating through the previous lines?
File namefile = new File(root, ".name");
FileReader namereader = new FileReader(namefile);
BufferedReader in = new BufferedReader(namereader);

You can use BufferedReader.readLine() to get the first line.
Note that the next call to readLine() will get you the 2nd line, and the next the 3rd line....
EDIT:
If you want to specify a specific line, as your comment suggest - you might want to use Apache Commons FileUtils, and use: FileUtils.readLines(). It will get you a List<String> which you can handle like any list, including getting a specific line. Note that it has more overhead because it reads the entire file, and populates a List<String> with its lines.

Um, what's wrong with BufferedReader.readLine()?
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
(I don't see any sign of a readFile() method though - what documentation were you looking at?)
Personally I prefer to use FileInputStream wrapped in InputStreamReader instead of FileReader by the way, as otherwise it will always use the platform default encoding - are you sure what's what you want?

final File namefile = new File(root, ".name");
final FileReader namereader = new FileReader(namefile);
final BufferedReader in = new BufferedReader(namereader);
in.readLine();

If you use the BufferedReader to read the File there should be a Method called
readLine()
wich reads exactly one Line.
http://developer.android.com/reference/java/io/BufferedReader.html

See the readline() method of the BufferedReader.
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html#readLine%28%29

Related

Read single line from FTP server without downloading whole file using it.sauronsoftware.ftp4j.FTPClient

How can we read single line from FTP server without downloading whole file using it.sauronsoftware.ftp4j.FTPClient.
Now, I am downloading whole file and than reading first line of file, is there any way we can read first line of file without download file in local machine. It should use only it.sauronsoftware.ftp4j
#http://www.sauronsoftware.it/projects/ftp4j/manual.php
NOTE : It should use it.sauronsoftware.ftp4j.FTPClient and not apache.
Mohit,
Use the Socket dtConnection; dtConnection.getInputStream(); of ftp4j.FTPClient you will get InputStream, Using that InputStream you can read first line of.
you can find below Example hoe to read first line using InputStream
BufferedReader bufferedReader = null;
String firstLine = null;
bufferedReader = new BufferedReader(new InputStreamReader(this.dataTransferInputStream, "UTF-8"));
firstLine = bufferedReader.readLine();
Hope this solution will work for you.
You could make your own stream class that throws an exception after it has the first line written to it.
Edit: or it could call abortCurrentDataTransfer() after it received the first line.

Inserting New Lines when Writing to a Text File in Java

I have a slight delema with learning FileWriter... The ultimate goal is writing a program that will "spawn" a .bat file that will be executed by the batch code that launched the .jar. The problem is, I have no clue how to make sure that every FileWriter.write(); will print on a new line... Any ideas??
To create new lines, simply append a newline character to the end of the string:
FileWriter writer = ...
writer.write("The line\n");
Also, the PrintWriter class provides methods which automatically append newline characters for you (edit: it will also automatically use the correct newline string for your OS):
PrintWriter writer = ...
writer.println("The line");
Use a BufferedWriter and use writer.newLine() after every write-operation that represents one line.
Or, use a PrintWriter and writer.println().
If you are using BufferedWriter then you can use an inbuilt method :
BufferedWriter writer = Files.newBufferedWriter(output, charset);
writer.newLine();

File and Filewriter

I need a way to delete a line, im using this to write on the file:
FileWriter insert = new FileWriter(file, true);
PrintWriter out = new PrintWriter(insert);
out.println("1. Mario");
I made a thing that reads line by line but i've no idea how to delete the string that returns, is that even possible?
While you're reading in the lines of text write then lines you want to keep to a StringBuffer or StringBuilder then write the contents of the buffer/builder back to the file. Is there any specific reason that you're opening up the file for appending when you're wanting to remove lines of text from the file or am I missing something?

java- read last 2 lines in a file and delete last line, then add 2 fixed string values at end of file

I want to read the last 2 lines in some files, and if the content of second last line matches a specific string, then delete the last line only.
Also, after the above operation, 2 lines of data have to be appended to the end of the modified file. I saw other questions on SO that deal with different parts of my problem, but is there an easy way of doing all of the above with minimal code, preferably in a single function? (I can combine the different functions available at SO but that would be messy...)
I would recommend you to do it "in memory". It's easy to read line by line into a List, check the last lines and update the lines and write it back to the file.
Example:
public static void main(String[] args) throws IOException {
String fileName = "test.txt";
List<String> lines = new ArrayList<String>();
// read the file into lines
BufferedReader r = new BufferedReader(new FileReader(fileName));
String in;
while ((in = r.readLine()) != null)
lines.add(in);
r.close();
// check your condition
String secondFromBottom = lines.get(lines.size() - 2);
if (secondFromBottom.matches("Hello World!")) {
lines.remove(lines.size() - 1);
lines.add("My fixed string");
}
// write it back
PrintWriter w = new PrintWriter(new FileWriter(fileName));
for (String line : lines)
w.println(line);
w.close();
}
Note: No exception handling is done in the example above... you need to handle cases where the file for example doesn't contain two lines and other problems!
If you have really big files and perfomance is an issue the way to go is to use a RandomAccessFile and read backwards looking for the line termination bytes to determine where the last two lines begin. Otherwise use dacwe's approach.
As Gandalf said you can:
take RandomAccessFile,
use method seek(long) to jump forward and read those lines. But you won't know exactly how big the jump should be.
to delete last lines you need the position of begin of last line so before reading each line store their file pointer position (method getFilePointer()). Deleting to that position you use setLength(long).
My example of reading and deleting last lines you have here:
Deleting the last line of a file with Java
Useful can be also:
Quickly read the last line of a text file?

How to append to the end of a file in java?

...
Scanner scan = new Scanner(System.in);
System.out.println("Input : ");
String t = scan.next();
FileWriter kirjutamine = new FileWriter("...");
BufferedWriter out = new BufferedWriter(writing);
out.write(t)
out.close();
...
if I write sometring into the file, then it goes to the first line. But if run the programm again, it writes the new text over the previous text (into the first line). I want to do: if I insert something, then it goes to the next line. For example:
after 1 input) text1
after 2 input) text1
text2
and so on...
what should i change in the code?
thanks!
java.io.PrintWriter pw = new PrintWriter(new FileWriter(fail, true));
This should do it. Use that over the existing pw line.
edit: And as explained in the comments, this is causing the following things to happen:
A FileWriter is being created, with the optional 'append' flag being set to true. This causes FileWriter to not overwrite the file, but open it for append and move the pointer to the end of the file.
PrintWriter is using this FileWriter (as opposed to creating its own with the file you pass it.)
(A lot of editing going on here. I was uncertain about the question a few times.)
I suggest you use the append flag in the FileWriter constructor.
You also might line to add a newline between each write ;)
why dont you use RandomAccessFile?
In RandomAccessFile, read/write operations can be performed at any position.The file pointer can be moved to anyplace by seek() method. You have to specify file opening mode while using it.
Example:
RandomAccessFile raf = new RandomAccessFile("anyfile.txt","rw"); // r for read and rw for read and write.
and to take the file pointer to EOF you have to use seek().
raf.seek(raf.length());
Instead of using BufferedWriter, use
PrintWriter out = new PrintWriter(kirjutamine);
out.print(t);
out.close();

Categories