Read a particuliar line in txt file in Java - java

The file ListeMot.txt contain 336529 Line
How to catch a particular line.
This my code
int getNombre()
{
nbre = (int)(Math.random()*336529);
return nbre ;
}
public String FindWord () throws IOException{
String word = null;
int nbr= getNombre();
InputStreamReader reader = null;
LineNumberReader lnr = null;
reader = new InputStreamReader(new FileInputStream("../image/ListeMot.txt"));
lnr = new LineNumberReader(reader);
word = lnr.readLine(nbr);
}
Why I can't get word = lnr.readLine(nbr);??
Thanks
P.S I am new in java!

To get the Nth line you have to read all the lines before it.
If you do this more than once, the most efficient thing to do may be to load all the lines into memory first.
private final List<String> words = new ArrayList<String>();
private final Random random = new Random();
public String randomWord() throws IOException {
if (words.isEmpty()) {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("../image/ListeMot.txt")));
String line;
while ((line = br.readLine()) != null)
words.add(line);
br.close();
}
return words.get(random.nextInt(words.size()));
}
BTW: The the parameter theWord meant to be used?

There is no method like readLine(int lineNumber) in Java API. You should read all previous lines from a specific line number. I have manipulated your 2nd method, take a look at it:
public void FindWord () throws IOException
{
String word = "";
int nbr = getNombre();
InputStreamReader reader = null;
LineNumberReader lnr = null;
reader = new InputStreamReader( new FileInputStream( "src/a.txt" ) );
lnr = new LineNumberReader( reader );
while(lnr.getLineNumber() != nbr)
word = lnr.readLine();
System.out.println( word );
}
The above code is not error free since I assume you know the limit of the line number in the given text file, i.e. if we generate a random number which is greater than the actual line number, the code will go into an infinite loop, be careful.
Another issue, line numbers start from 1 so I suggest you to change your random line number generator method like this:
int getNombre()
{
nbre = (int)(Math.random()*336529) + 1;
return nbre ;
}

The LineNumberReader only keeps track of the number of lines read, it does not give random access to lines in the stream.

Related

How would I transfer 5-letter words into a new text file?

Let's say I have a txt file that has the whole dictionary in it. how would I make this code be able to transer only 5-letter words into a new created txt file?
import java.io.*;
public class wordwebster {
public static void main(String[] args) throws IOException {
int five = 0;
File directory = new File(".");
String webster = directory.getCanonicalPath() + File.separator+ "webster.txt";
String fiveLetterWords = directory.getCanonicalPath()+ File.separator +"fiveLetterWords.txt";
File fin = new File(webster);
FileInputStream file = new FileInputStream(fin);
BufferedReader input = new BufferedReader(new InputStreamReader(file));
FileWriter fileStream = new FileWriter(fiveLetterWords,true);
BufferedWriter output = new BufferedWriter(fileStream);
String line = null;
while ((line = input.readLine())!= null){
output.write(line);
output.newLine();
}
input.close();
output.close();
}
}
EDIT:
As asked, let's say the input file (webster.txt) contain the words
Sentence
Frequent
Hello
Send
Variety
False
I would need only five letter words be extracted (Hello and False) and be put into a new file (fiveLetterWords.txt).
If you need to allow only words whose length is exactly five, you can just put an if condition to check before writing into file. Modify your while loop to this,
while ((line = input.readLine()) != null) {
if (line.trim().length() == 5) {
output.write(line);
output.newLine();
}
}
Hope this helps. Let me know if you face any issues.

Saving huge file in a string JAVA

i'm trying to read a FASTA file into a string in java.
My code works fine with small files, but when I choose a real FASTA file
which includes 5 million chars, so I can use this string, the program get stucked. get stucked= i see no output, and the program becomes with black screen.
public static String ReadFastaFile(File file) throws IOException{
String seq="";
try(Scanner scanner = new Scanner(new File(file.getPath()))) {
while ( scanner.hasNextLine() ) {
String line = scanner.nextLine();
seq+=line;
// process line here.
}
}
return seq;
}
Try to use a StringBuilder to process big loads of text data:
public static String ReadFastaFile( File file ) throws IOException {
StringBuilder seq = new StringBuilder();
try( Scanner scanner = new Scanner( file ) ) {
while ( scanner.hasNextLine() ) {
String line = scanner.nextLine();
seq.append( line );
// process line here.
}
}
return seq.toString();
}
I would try to use BufferedReader to read the file, something like this:
public static String readFastaFile(File file) throws IOException {
String seq="";
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process line here.
}
}
return seq;
}
And also concatenate with StringBuilder like davidbuzatto said.

Reading a specific set of lines in a file [duplicate]

In Java, is there any method to read a particular line from a file? For example, read line 32 or any other line number.
For small files:
String line32 = Files.readAllLines(Paths.get("file.txt")).get(32)
For large files:
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
line32 = lines.skip(31).findFirst().get();
}
Unless you have previous knowledge about the lines in the file, there's no way to directly access the 32nd line without reading the 31 previous lines.
That's true for all languages and all modern file systems.
So effectively you'll simply read lines until you've found the 32nd one.
Not that I know of, but what you could do is loop through the first 31 lines doing nothing using the readline() function of BufferedReader
FileInputStream fs= new FileInputStream("someFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
for(int i = 0; i < 31; ++i)
br.readLine();
String lineIWant = br.readLine();
Joachim is right on, of course, and an alternate implementation to Chris' (for small files only because it loads the entire file) might be to use commons-io from Apache (though arguably you might not want to introduce a new dependency just for this, if you find it useful for other stuff too though, it could make sense).
For example:
String line32 = (String) FileUtils.readLines(file).get(31);
http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#readLines(java.io.File, java.lang.String)
You may try indexed-file-reader (Apache License 2.0). The class IndexedFileReader has a method called readLines(int from, int to) which returns a SortedMap whose key is the line number and the value is the line that was read.
Example:
File file = new File("src/test/resources/file.txt");
reader = new IndexedFileReader(file);
lines = reader.readLines(6, 10);
assertNotNull("Null result.", lines);
assertEquals("Incorrect length.", 5, lines.size());
assertTrue("Incorrect value.", lines.get(6).startsWith("[6]"));
assertTrue("Incorrect value.", lines.get(7).startsWith("[7]"));
assertTrue("Incorrect value.", lines.get(8).startsWith("[8]"));
assertTrue("Incorrect value.", lines.get(9).startsWith("[9]"));
assertTrue("Incorrect value.", lines.get(10).startsWith("[10]"));
The above example reads a text file composed of 50 lines in the following format:
[1] The quick brown fox jumped over the lazy dog ODD
[2] The quick brown fox jumped over the lazy dog EVEN
Disclamer: I wrote this library
Although as said in other answers, it is not possible to get to the exact line without knowing the offset (pointer) before. So, I've achieved this by creating an temporary index file which would store the offset values of every line. If the file is small enough, you could just store the indexes (offset) in memory without needing a separate file for it.
The offsets can be calculated by using the RandomAccessFile
RandomAccessFile raf = new RandomAccessFile("myFile.txt","r");
//above 'r' means open in read only mode
ArrayList<Integer> arrayList = new ArrayList<Integer>();
String cur_line = "";
while((cur_line=raf.readLine())!=null)
{
arrayList.add(raf.getFilePointer());
}
//Print the 32 line
//Seeks the file to the particular location from where our '32' line starts
raf.seek(raf.seek(arrayList.get(31));
System.out.println(raf.readLine());
raf.close();
Also visit the Java docs on RandomAccessFile for more information:
Complexity: This is O(n) as it reads the entire file once. Please be aware for the memory requirements. If it's too big to be in memory, then make a temporary file that stores the offsets instead of ArrayList as shown above.
Note: If all you want in '32' line, you just have to call the readLine() also available through other classes '32' times. The above approach is useful if you want to get the a specific line (based on line number of course) multiple times.
Another way.
try (BufferedReader reader = Files.newBufferedReader(
Paths.get("file.txt"), StandardCharsets.UTF_8)) {
List<String> line = reader.lines()
.skip(31)
.limit(1)
.collect(Collectors.toList());
line.stream().forEach(System.out::println);
}
No, unless in that file format the line lengths are pre-determined (e.g. all lines with a fixed length), you'll have to iterate line by line to count them.
In Java 8,
For small files:
String line = Files.readAllLines(Paths.get("file.txt")).get(n);
For large files:
String line;
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
line = lines.skip(n).findFirst().get();
}
In Java 7
String line;
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
for (int i = 0; i < n; i++)
br.readLine();
line = br.readLine();
}
Source: Reading nth line from file
If you are talking about a text file, then there is really no way to do this without reading all the lines that precede it - After all, lines are determined by the presence of a newline, so it has to be read.
Use a stream that supports readline, and just read the first X-1 lines and dump the results, then process the next one.
It works for me:
I have combined the answer of
Reading a simple text file
But instead of return a String I am returning a LinkedList of Strings. Then I can select the line that I want.
public static LinkedList<String> readFromAssets(Context context, String filename) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));
LinkedList<String>linkedList = new LinkedList<>();
// do reading, usually loop until end of file reading
StringBuilder sb = new StringBuilder();
String mLine = reader.readLine();
while (mLine != null) {
linkedList.add(mLine);
sb.append(mLine); // process line
mLine = reader.readLine();
}
reader.close();
return linkedList;
}
Use this code:
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileWork
{
public static void main(String[] args) throws IOException {
String line = Files.readAllLines(Paths.get("D:/abc.txt")).get(1);
System.out.println(line);
}
}
You can use LineNumberReader instead of BufferedReader. Go through the api. You can find setLineNumber and getLineNumber methods.
You can also take a look at LineNumberReader, subclass of BufferedReader. Along with the readline method, it also has setter/getter methods to access line number. Very useful to keep track of the number of lines read, while reading data from file.
public String readLine(int line){
FileReader tempFileReader = null;
BufferedReader tempBufferedReader = null;
try { tempFileReader = new FileReader(textFile);
tempBufferedReader = new BufferedReader(tempFileReader);
} catch (Exception e) { }
String returnStr = "ERROR";
for(int i = 0; i < line - 1; i++){
try { tempBufferedReader.readLine(); } catch (Exception e) { }
}
try { returnStr = tempBufferedReader.readLine(); } catch (Exception e) { }
return returnStr;
}
you can use the skip() function to skip the lines from begining.
public static void readFile(String filePath, long lineNum) {
List<String> list = new ArrayList<>();
long totalLines, startLine = 0;
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
totalLines = Files.lines(Paths.get(filePath)).count();
startLine = totalLines - lineNum;
// Stream<String> line32 = lines.skip(((startLine)+1));
list = lines.skip(startLine).collect(Collectors.toList());
// lines.forEach(list::add);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
list.forEach(System.out::println);
}
EASY WAY - Reading a line using line number.
Let's say Line number starts from 1 till null .
public class TextFileAssignmentOct {
private void readData(int rowNum, BufferedReader br) throws IOException {
int n=1; //Line number starts from 1
String row;
while((row=br.readLine()) != null) { // Reads every line
if (n == rowNum) { // When Line number matches with which you want to read
System.out.println(row);
}
n++; //This increments Line number
}
}
public static void main(String[] args) throws IOException {
File f = new File("../JavaPractice/FileRead.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
TextFileAssignmentOct txf = new TextFileAssignmentOct();
txf.readData(4, br); //Read a Specific Line using Line number and Passing buffered reader
}
}
for a text file you can use an integer with a loop to help you get the number of the line, don't forget to import the classes we are using in this example
File myObj = new File("C:\\Users\\LENOVO\\Desktop\\test.txt");//path of the file
FileReader fr = new FileReader(myObj);
fr.read();
BufferedReader bf = new BufferedReader(fr); //BufferedReader of the FileReader fr
String line = bf.readLine();
int lineNumber = 0;
while (line != null) {
lineNumber = lineNumber + 1;
if(lineNumber == 7)
{
//show line
System.out.println("line: " + lineNumber + " has :" + line);
break;
}
//lecture de la prochaine ligne, reading next
line = bf.readLine();
}
They are all wrong I just wrote this in about 10 seconds.
With this I managed to just call the object.getQuestion("linenumber") in the main method to return whatever line I want.
public class Questions {
File file = new File("Question2Files/triviagame1.txt");
public Questions() {
}
public String getQuestion(int numLine) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
for(int i = 0; i < numLine; i++) {
line = br.readLine();
}
return line; }}

Reading two files and then finding the growth rate

I need help trying to read two files that have the census from 2010 and 2000. I have to read both files and then find out the population growth between those two files. I keep getting null for ever single state. I know that I have null for inLine1 and inLine2.
The file looks like this
Alabama,4779736
Alaska,710231
Arizona,6392017
Arkansas,2915918
Code:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class pa10
{
public static void main(String[] args, char[] inLine2, char[] inLine1)
throws java.io.IOException
{
String fileName1 = "Census2000growth.txt";
String fileName2 = "Census2010growth.txt";
int i;
File f = new File("Census2010growth.txt");
if(!f.exists()) {
System.out.println( "file does not exist ");
}
Scanner infile = new Scanner(f);
infile.useDelimiter ("[\t|,|\n|\r]+"); //create a delimiter
final int MAX = 51;
int [] myarray = new int [MAX];
String[] statearray = new String[MAX];
int fillsize;
// set up input stream1
FileReader fr1 = new
FileReader(fileName1);
// buffer the input stream
BufferedReader br1 =
new BufferedReader(fr1);
// set up input stream2
FileReader fr2 = new
FileReader(fileName2);
// buffer the input stream
BufferedReader br2 =
new BufferedReader(fr2);
// read and display1
String buffer1 = "";
ArrayList<String> firstFile1 = new ArrayList<String>();
while ((buffer1 = br1.readLine()) != null) {
firstFile1.add(buffer1);
System.out.println(inLine1); // display the line
}
br1.close();
//Now read the second file or make for this separate method
// read and display2
String buffer2 = "";
ArrayList<String> firstFile2 = new ArrayList<String>();
while ((buffer2 = br2.readLine()) != null) {
firstFile2.add(buffer2);
System.out.println(inLine2); // display the line
}
br2.close();
//Read all the lines in array or list
//After that you can calculate them.
}
}
Read the BufferedReader documentation. Your file isn't formatted with the types of line separators it is expecting. I suggest using a Scanner and setting the line separator to the appropriate pattern, or using String.split
You have two different variables, buffer1 and inline1. Since you never set the value of inline1, it will always be null.

Java - Create String Array from text file [duplicate]

This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 1 year ago.
I have a text file like this :
abc def jhi
klm nop qrs
tuv wxy zzz
I want to have a string array like :
String[] arr = {"abc def jhi","klm nop qrs","tuv wxy zzz"}
I've tried :
try
{
FileInputStream fstream_school = new FileInputStream("text1.txt");
DataInputStream data_input = new DataInputStream(fstream_school);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
String[] itemsSchool = str_line.split("\t");
}
}
}
catch (Exception e)
{
// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Anyone help me please....
All answer would be appreciated...
If you use Java 7 it can be done in two lines thanks to the Files#readAllLines method:
List<String> lines = Files.readAllLines(yourFile, charset);
String[] arr = lines.toArray(new String[lines.size()]);
Use a BufferedReader to read the file, read each line using readLine as strings, and put them in an ArrayList on which you call toArray at end of loop.
Based on your input you are almost there. You missed the point in your loop where to keep each line read from the file. As you don't a priori know the total lines in the file, use a collection (dynamically allocated size) to get all the contents and then convert it to an array of String (as this is your desired output).
Something like this:
String[] arr= null;
List<String> itemsSchool = new ArrayList<String>();
try
{
FileInputStream fstream_school = new FileInputStream("text1.txt");
DataInputStream data_input = new DataInputStream(fstream_school);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
itemsSchool.add(str_line);
}
}
arr = (String[])itemsSchool.toArray(new String[itemsSchool.size()]);
}
Then the output (arr) would be:
{"abc def jhi","klm nop qrs","tuv wxy zzz"}
This is not the optimal solution. Other more clever answers have already be given. This is only a solution for your current approach.
This is my code to generate random emails creating an array from a text file.
import java.io.*;
public class Generator {
public static void main(String[]args){
try {
long start = System.currentTimeMillis();
String[] firstNames = new String[4945];
String[] lastNames = new String[88799];
String[] emailProvider ={"google.com","yahoo.com","hotmail.com","onet.pl","outlook.com","aol.mail","proton.mail","icloud.com"};
String firstName;
String lastName;
int counter0 = 0;
int counter1 = 0;
int generate = 1000000;//number of emails to generate
BufferedReader firstReader = new BufferedReader(new FileReader("firstNames.txt"));
BufferedReader lastReader = new BufferedReader(new FileReader("lastNames.txt"));
PrintWriter write = new PrintWriter(new FileWriter("emails.txt", false));
while ((firstName = firstReader.readLine()) != null) {
firstName = firstName.toLowerCase();
firstNames[counter0] = firstName;
counter0++;
}
while((lastName= lastReader.readLine()) !=null){
lastName = lastName.toLowerCase();
lastNames[counter1]=lastName;
counter1++;
}
for(int i=0;i<generate;i++) {
write.println(firstNames[(int)(Math.random()*4945)]
+'.'+lastNames[(int)(Math.random()*88799)]+'#'+emailProvider[(int)(Math.random()*emailProvider.length)]);
}
write.close();
long end = System.currentTimeMillis();
long time = end-start;
System.out.println("it took "+time+"ms to generate "+generate+" unique emails");
}
catch(IOException ex){
System.out.println("Wrong input");
}
}
}
You can read file line by line using some input stream or scanner and than store that line in String Array.. A sample code will be..
File file = new File("data.txt");
try {
//
// Create a new Scanner object which will read the data
// from the file passed in. To check if there are more
// line to read from it we check by calling the
// scanner.hasNextLine() method. We then read line one
// by one till all line is read.
//
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//store this line to string [] here
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner scanner = new Scanner(InputStream);//Get File Input stream here
StringBuilder builder = new StringBuilder();
while (scanner.hasNextLine()) {
builder.append(scanner.nextLine());
builder.append(" ");//Additional empty space needs to be added
}
String strings[] = builder.toString().split(" ");
System.out.println(Arrays.toString(strings));
Output :
[abc, def, jhi, klm, nop, qrs, tuv, wxy, zzz]
You can read more about scanner here
You can use the readLine function to read the lines in a file and add it to the array.
Example :
File file = new File("abc.txt");
FileInputStream fin = new FileInputStream(file);
BufferedReader reader = new BufferedReader(fin);
List<String> list = new ArrayList<String>();
while((String str = reader.readLine())!=null){
list.add(str);
}
//convert the list to String array
String[] strArr = Arrays.toArray(list);
The above array contains your required output.

Categories