line 1 « Development « Java I/O Q&A

1. Number of lines in a file in Java

I use huge data files, sometimes I only need to know the number of lines in these files, usually I open them up and read them line by line until I ...

2. What is the fastest way to find out how many non-empty lines are in a file, using Java?

What is the fastest way to find out how many non-empty lines are in a file, using Java?

3. Putting each attribute on a new line during xml serialization

Lets say I have a DOM object (or a string containing xml). Is it in any way possible to serialize the xml in such a way that each attribute appears on ...

4. How can I get the count of line in a file in an efficient way?

I have a big file. It includes approximately 3.000-20.000 lines. How can I get the total count of lines in the file using Java?

5. Remove line from big txtfile in Java

Does anybody know how to remove a line from a textfile. I'm looking for something else than u read and write line by line and skip the line you want te remove. For ...

6. Java - Find a line in a file and remove

I was digging on the internet to find a small code snippet that will find a line in file and remove that line (not content but line) but could not find. ...

7. deleting lines from a file

I need to delete certain lines from a file, the file is a list of contacts that I read in from a file into my GUI. When I get to ...

8. How to remove line breaks from a file in Java?

How can I replace all line breaks from a string in Java in such a way that will work on Windows and Linux (ie no OS specific problems of carriage return/line ...

9. command_line argument

I can not get the difference between these sentences! would you please write some snippet code for these sentences?thanks

  • The program will receive a path to a directory as the first command-line ...

10. In Java, how to read from a file a specific line, given the line number?

In Java, is there any method to read a particular line from a file, for example, read line 32?

11. Difficulty while finding no of lines in a file using java?

While find out no of line in a file, it displays more number of lines. for example in my file having only 26 line in word document. But while count using java ...

12. How to plot the graph(line) from a file in java?

I have a directory containing list of files. Those files have some list of values as x and y ordered as line by line. And my question is just I would like to ...

13. Delete a line from a file in java

Ok, so I'm trying to delete lines from a text file with java. Currently the way I'm doing this, is I'm keep track of a line number and inputting an index. ...

14. Prepend lines to file in Java

Is there a way to prepend a line to the File in Java, without creating a temporary file, and writing the needed content to it?

15. Read Lines between a start index and end index in java

Lets say I have 10 lines in a file. I have 2 parameters that specify the beginning and ending of a index. StartIndex = 2 // specifies the first 2 lines EndIndex = ...

16. Fastest Java way to remove the first/top line of a file (like a stack)

I am trying to improve an external sort implementation in java. I have a bunch of BufferedReader objects open for temporary files. I repeatedly remove the top line from each ...

17. Java Line separator File .ext separator

i am wondering regarding Java: is there a file extension separator? like *.doc, the "." being the question. i know there is a line.separator. just would like my app to be portable so ...

18. Search a string in a file and write the matched lines to another file in Java

For searching a string in a file and writing the lines with matched string to another file it takes 15 - 20 mins for a single zip file of 70MB(compressed state). Is there ...

19. what is the best way to read single line files in Java

As the title itself says, is it necessary to create buffered reader while loop and all to read single line file? its also constant never changes

20. Reading line from a file, and manipulating individual words from each line?

I am attempting to the read-in a .txt file and create a map to calculate total property listed in dollars and cents for each agent id. The agent ids are ...

21. Can we replace a line from file with other line (i.e. new string) having different size?


zzzzzz      <- replaced aa by zzzzzz

22. Getting the new line character without System.getProperty("line.separator")?

I want to create a text file, than load it up without any newlines or spaces (This is for a simple RPG). So I want to test for all 3 major ...

23. in java how to efficiently read x lines from a file, close it, and then open it again, starting at line x and continue reading

BufferedReader has easy methods for reading a file line by line. But there doesn't seem to be anyway to keep track of where you are, so you can get back ...

24. java: jumping to a line and reading it (updated)

I have to work with big files (many GB) and need quick lookups to retrieve specific lines on request. The idea has been to maintain a mapping:

some_key -> byte_location
Where the byte location ...

25. Java : Read last n lines of a HUGE file

I want to read the last n lines of a very big file without reading the whole file into any buffer/memory area using Java. I looked around the JDK APIs and Apache ...

26. Automating deleting lines of code from .java file, script

As part of code cleanup, and migrating to new test framework, I need to delete constructor which has argument 'String name' from all the test classes(Almost 1000+ *.java files). For example ...

27. Passing a file as a command line argument and reading its lines

Hi this is the code that i have found in the internet for reading the lines of a file and also I use eclipse and I passed the name of files as ...

28. removing lines from a file

I've got the following code but it doesn't seem to be working.. anyone have any ideas why? basically I'm creating a new file containing all the lines except those which contain ...

29. Highest Frequency of Letter(s) in each Line of File-Core Java Programming

StackOverflow people, Need Java Advice and Code which reads a file(File.txt) and prints to the console a list of all the letters that occurred with the highest frequency in each line ...

30. java line breaks in file

I am trying to write a file line by line using apache FileUtils.writeLines()
When I try to open the file (notepad++, editplus) it is with no line breaks.
(I am sending null to ...

31. Edit files single line in java

I'm trying to edit configuration file in Java. What I really need to do is to change single line, so reading the whole file and writing it back would be waste ...

32. Read each line from a file, creating ints from it

I have a file called membercodes.cfg. I want to read each line (lines are like this: 555:333:989) to be read. Then, the line must be split in 3 parts. Integer 1 must be valued ...

33. Why Doesn't This Java Code Skip Lines with #?

I'm a bit of a newbee but I'm trying to allow an external .txt file that is read by a Java script be able to have some comments in the beginning ...

34. Write specific line into file

I'm trying to write line into a file at line-position n. Even if line n isn't present. In that case the file has to grow with empty lines to reach n. ...

35. Preventing the NoSuchElementException when reading from a file with no spare line

I am trying to find a way to deal with the NoSuchElementException error thrown by a Scanner object when reading the last item in my text file with NO SPARE LINE. ...

36. Java Line IO vs C++ IO?

Note that this is NOT a "better-than" discussion. I'm a C++ programmer, and it makes me feel incredibly dumb not to know how to do very much Java file IO. I need to ...

37. How can I make all the lines of a very big file the same length in java?

I have a very big file. The length of the longest line of my file is 9. I want to read my file with RandomAccessFile and be able to seek to ...

38. how to know on which line of the file an IOexception has happened

In my program i want to read from a text file. the data in my files are numbers which are separated by space . i will convert them to integer in ...

39. Ignore a line while reading a file in java

I have some code to read the lines from a file, I would like to recognize when the line starts or the fisrt character (not blank) is '*' and ignore ...

40. Java Formatter not allowing new line character?

So, I've got the following code to write to a file:

Formatter output = ....... // Creating the formatter works, writes to appropriate file.

output.format("%d\n", records.length);
for(GradeRecord gR:records)
    output.format(gR.toString() + "\n");
Only ...

41. How do I read the third value from each line of a file in Java?

I'm handling a loan monitoring system project, and in this project customer details will be saved in a text file with a row for each customer like:

sri chennai 10000 asda ...

42. new line not inserted

This is the snippet:

String s1=new String("");
String s2=new String("" + "\n" + "");
byte buffer1[]=s1.getBytes();
byte buffer2[]=s2.getBytes();
FileOutputStream fos=new FileOutputStream("f1.txt");
for(int i=0;i<buffer1.length;i++)
FileOutputStream fos2=new FileOutputStream("f2.txt");
for(int i=0;i<buffer2.length;i++)
System.out.println("size of buffer1 = "+buffer1.length);
System.out.println("\nsize of buffer2 = ...

43. how do i covert the line read in the file to "_"s?

I'm trying to create a hangman program that uses file io/ file input. I want the user to choose a category (file) which contains 4 lines; each has one word. The ...

44. read from file and display random line

Im trying to get my android application to read from a text file and randomly chose an entry and then display it, How do i go about doing this? I think ...

45. How to remove a line from a file by knowing its position?

I want to remove a line from my file (specifically the second line) so I have used another file to copy in it ,but using the following code the second file contain ...

46. Reading variable number of lines from file

How do I read multiple lines (in Java) from an input file (say, The input file does not have a fixed number of lines, it can have anywhere from 3 to ...

47. Java code for tail n lines of file equivalent to tail commad in unix

Following is the code written for tailing 'n' no of lines of a file.


import java.util.HashMap;
import java.util.Map;

class TailCommand {
public static void main(String args[]) {
    int j;

48. Format XML, one attribute per line, with JDom

I use JDom for XML parsing / formatting. I would like long lines of attributes to be split into several lines. Like :

<node att1="Foo" att2="Bar" att3="Foo" />
Into :

49. How to write a file in new line using java code

I having a text like Apple|MicroSoft|Oracle|Windows|Mac|.I wish to print like Apple Microsoft Oracle Windows Mac. I used .split() keword, but it prints like, A p p l e | M i c r o s o f t | ... why it will print like this if any alternate solution for this. Thanks in advance. ...

50. How can I jump to specific line and read from that in java

I meet a big file(much GB),and I want to jump to specific line directly, and then read some line from that... for example, I hava file like

and want to read lines from ...

51. why the other part is not printed in the next line?

From the following code :


class fileTester {
  public static void main( String args[]) throws IOException {
    String string = "Suhail" + "\n" + "gupta";

52. Deleting a line from a file

Please help to solve this problem. I want to delete every line from a file after reading that line. Can we delete like this? I don't want use any temporary file to do ...

53. How can I replace the first line of a large file in Java?

I would like to blank out the first line of a text file in Java. This file is several gigabytes and I do not want to do a copy. ...

54. How to read String Builder line by line

Can I read String Builder line by line? And Get the length of each line as well.

EDIT: "I build string in StringBuilder and add "\n" within. And I need to read it ...

55. Remove all blank spaces and empty lines

How to remove all blank spaces and empty lines from a txt File using Java SE? Input:



56. Java read line from file

My program must read text files - line by line. Files in UTF-8. I am not sure that files are correct - can contain unprintable characters. Is possible check for it without going to ...

57. how to insert the new line in the file after specified line using java program

how to insert the new line in the file after specified line using java program Please help me on this with an example. Thanks.

58. Java: How to count the no. of lines in a file?

Possible Duplicate:
Number of lines in a file in Java
I need to count the number of lines of a txt file that is passed to ...

59. to find shortest and longest lines in a file

write a program to read a text file and print out the first shortest and first longest line of that file with their line numbers.Program should read the file name as ...

60. Java java.nio writes line of []s

I am using java.nio to copy a file, it copies fine except for the fact that there is a line of []s at the end of the file. Here is my code:

source ...

61. Java: Get random line from a big file

I've seen how to get a random line from a text file, but the method stated there (the accepted answer) is running horrendously slow. It runs very slowly on my ...

62. Java how to remove one line in a file?

I want to delete one line of record in a File using Java, example in my file,

studentID  studentName studentAddress studentPhoneNo

63. 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 ...

64. Scanner No Line Found Exception

I am getting the following exception. java.util.NoSuchElementException: No line found I got this error while writing a larger program which needed to read from a text file, and so decided to do a ...

65. First longest and shortest line in file

I have a problem in java. I have to write a program which will read a file and it will check for the first longest line and first shortest line. And then ...

66. How to write lines to a file, and each line is a atomic operation?

I want to write some lines to a file, and I need each line of writing is a atomic operation. For example, I have 3 lines:

When I write them into a file ...

67. How to print certain lines from a file that begin and end with a conditional string

I have a .txt file like this:

There is 
a lot of
contents here 

Here are 
many other

and bunch of 
contents here too
I want to print out the contents between the tagged strings, ...

68. getting a "^M" after each line in unix from a java created file

I have a Java program that creates a file and prints a bunch of data using this statement:

When I view this file in vim in Unix I see a ^M after ...

69. Read line using Java New I/O

What's the best way to read a line from a file using the New I/O ? I can only get a byte at a time. Any idea?

70. Reading next line in Java

There seem to be multiple ways of doing I/O in Java. How does one decide which one to use. For example: I can accept user's input through stdin in the following two ways: ...

71. Writing a new line character

I have a simple program that opens a URL and copies that file into a temp file in the same directory the program is in. The problem is that the temp file doesn't output the new line characters. It just makes the file one really long line. Does anyone know how to read the new line and write it back to ...

72. deletion of space between two lines

hi, you can read the file line by line and write everithing but the empty lines to a second file. or you can read all to a Vector (all but the empty lines) and when done, you write the contents of the vector back to the same file. you can read the file by creating a BufferedReader Object. you can write ...

73. Why lines are not fully printed?

Hi I am trying to print the System.getProperties() output. Both to the console and also tried to store it in a file. But, for values that are really long ( I think in my system, more than 55 or so characters ), they are not fully printed, but instead the lines finish of with ... Can somebody explain this. I am ...

74. Reading every line from a file to string

I'm trying to parse a text file into equal length peaces..and put one space to separate words. if the next text is in the file "eka.txt" hello kathy howare you doing the outcome should be hello kathy how a re yo u doi ng How can i read every line from my text file ("eka.txt") now it only reads the first ...

75. how to read one line then delete that line ?

Dear All I hv a question if i hv a file and content of this file like belows /* This is first line */ /* This is second line*/ I need read line by line, every time only could read one line, and i need delete that line after reading it. How do I implement it? Regards

76. String to File? Del. one line in a file?

Hi,I have a xml file, which I want to add two lines and delete one line of it. For the adding lines, I will use stringbuffer and append method to add it as a whole string, but how can I change it back to a temp File for transferring? and How can I delete one line in my XML files? it ...

77. Last line

The File class has a method length() to get the number of bytes in a file. This is preferred - the available() method is not guaranteed to return all bytes in the file at once - only those that the system has immediate access to. What if the file is a fragmented disk file? For efficiency the system will let you ...

78. Is it better to write each line to a file or wait and write whole string

I have a large portion of text that needs to be written to a file. The text is generated dynamically based on the result set of query and other factors. The text result could be very large (about 220K). The question I have is it better to write out each line to the stream as I loop through the dynamic information, ...

79. Reading no of lines from a file

Hi, I was wondering if I can possibly read the contents of a given no of lines in a file (say 500 out of 1000 lines) into an array in a single step ? I can use the BufferedReader's readLine() in a for loop. But, is there any way to copy the contents of a given number of lines from a ...

80. insert new line character

Also, if you are talking about inserting the character just so you have the commands on separate lines, like: command one command two you can use the PrintWriter class, it has options to write both on the same line (the print() method), or write one command on one line, and then the next on a new line (the println() method). You ...

81. When printing, want to capture fact that printer off line

We have written an application that prints to a windows printer (LPT1). The code for the print method is below. It is written in java 1.3. When running on a windows 2000 machine, if the printer is offline (eg not connected, run out of paper etc) then a message is displayed - eg "device is not connected". However, when running on ...

82. How to read line by line

Hi, I hv .txt file and am reading the file through FileInputStream. .txt file like WYC911 21001858 xyz 1.00 WYC912 21001858 abc 1.00 WYC913 21001858 cde 1.00 I am able to read the txt file and getting the first line of the file and checking condition if input is (WYC911) doing some process. While am checking the second line value (WYC912) ...

83. A kinder, gentler API for reading lines

A kinder, gentler API for reading lines (I/O and Streams forum at JavaRanch) A friendly place for programming greenhorns! Register / Login Java Forums Java I/O and Streams A kinder, gentler API for reading lines Post by: Jim Yingst, Sheriff on Jan 26, 2003 16:33:00 Michael Matola recently made an interesting post in the Cattle Drive forum, here. I ...

85. Read and write last lines


When i'm appending to the text file... the text that i inserted appears after the last character of the file... But i wanted to insert a new line... so the text i'm appending must be a new line... I tried entering "\n" + my appended string but the file recognizes \n as a square like ([]) character....

87. wrap text with line break - Urgent

I have for example the code show below, but I want to be able to add line breaks. The reason si to better format paragraphs. Between paragraphs user wants to be able to put 1-4 lines between paragraphs and I need any help or ideas. Thanks again. import java.util.*;public class WordFormatter { public static String[] format(String paragraph, int length) { ...

88. remove one line from a file

89. Write CR/LF at the end of a line

Not sure what you mean by "CRLF that would be platform independent." "\n" will produce whatever is the traditional line ending for the host platform; one character on UNIX sytems (0x0A, or line feed); two characters on windows 0x0D 0x0A, or carriage return follwoed by line feed.) On Macintosh, at least in the old days, you'd get 0x0D alone! Anyway, using ...

90. how to read lines from a file

i have a txt file. ex: dmk.del.423543.dffd555.23434 dmk.del.423543.dffd555.23435 dmk.del.423543.dffd555.23436 dmk.del.423543.dffd555.23437 sample.txt i have to read the content of the sample txt file by line by line... Please let me know what modifications i have to do in the following code.. class SampelRead { public static void main(String[] args) { try{ BufferedReader br_reader = new BufferedReader(new FileReader("sample.txt")); String strin = br_reader.readLine(); System.out.println("Line ...

91. getting the first four characters from a line

I'm trying to search a file for a specific string that has been entered from a text field, find it and then display the first four characters from the line that it is in..... here is the code that I have now.... if(e1.getSource()==checkButton){ String SrNo; SrNo = String.valueOf(SerNo.getText()); try { BufferedReader in = new BufferedReader(new FileReader("wavail0.txt")); String str; while ((str = ...

92. How to read a file line by line?

Hi, I want to be able to read a file, from the file system line by, basically delimited by \n (new line character). Then I need to get the size of that line in bytes. And then I will do some processing with that line, which is basically appending it to a buffer with some massaging. What I don't want to ...

93. How to deal with Empty line followed by a content in ASC file

I am trying to read a text file, which has emplty lines in between and followed by text. I am encountering null pointer exception, whenever my readLine sees empty line. I am wondering if there is way to tackle this, so that that this empty space is ignored and it will proceed to next line. I am actually using POI from ...

94. Returning the last line in a file.

A friendly place for programming greenhorns! Register / Login Java Forums Java I/O and Streams Returning the last line in a file. Post by: Chris Ramsey, Ranch Hand on Dec 12, 2003 09:25:00 Hello all, I am attempting to return the last line of a file. Ultimately I would like to read in any specific line that I choose. ...

95. read file not include new line

I have tried to write data into a file.So, I read the file first using Buffered Reader and save them into a 2D array. Then, I use PrintWriter and write them into a file. In order to have a good looking, I use println. But, when I read that file again, the newline is included and counted to be a line. ...

96. Seek and Read specific line of a file

Hello All, Does anyone know an efficient way to find the beginning positions of each line in a file? I want to use the to go to the beginning of a specified line and read it. I am using it like a paging utility to show the contents of a line on a page. Thanks.

97. Reading 3 lines of text

My question is basically regarding readLine(). Incase I use- (System.out.println(bf.readLine()); will this print only the first line of text coming from the server? You have suggested I use a for loop. But why use a for loop? What does the counter ii denote here? Is it the number of sentences? And what happens if there are more sentences coming from the ...

98. trying ot read a line but instead reading a file

Ok I'm trying to read a file line by line and then check for instances of the line for display. Well it will read the file in but instead of reading from the line that I want it just reads from the first is a sample of what I have: import*; import java.util.*; import java.text.*; import java.math.*; public class ...

99. reading a file by lines

I works a lot with java, but I still have not clear anything about files. Can anybody send me a few lines describing how to read a text file by lines and how could I delete any of the lines or change it content or add a new line? Thank-you very much Gobellot

100. Not Recognizing the new line

Windows uses two characters, a carrage return and a line feed, to indicate a line. You should use BufferedWriter to write your file, as it is text (Streams are used for binary data) and that class provides a handy newLine() method to relieve you from the responsability of keeping track of which platform recognizes which line format.