What is the most efficient way to extract specific line numbers of data from a text file? For example, if I use the Scanner to parse a file, do I first have to create an array with a length matching the total number of lines in the text file?
If a text file has 30 lines and I only want to work with lines 3, 8, and 12, is there a way to specifically only read those lines?
here is how you do it:
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
int counter = 0;
// This will reference one line at a time
String line = null;
FileReader fileReader = null;
try {
// FileReader reads text files in the default encoding.
fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
counter++;
if(counter == 3 || counter == 8 || counter == 12)
{
// do your code
}
}
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
finally
{
if(fileReader != null){
// Always close files.
bufferedReader.close();
}
}
}
}
here is what you can do. (it is only part of your program, not exactly your program)
int counter 0 =;
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
counter++;
switch(counter){
case 3:
\\ do your code for line no 3
break;
case 8:
\\ do your code for line no 8
break;
case 12:
\\ do your code for line no 12
break;
}
}
br.close();
Try this
try
{
String sCurrentLine;
br = new BufferedReader(new FileReader("File_Path"));
int counter = 0;
while ((sCurrentLine = br.readLine()) != null)
{
counter++;
if (counter == 3 || counter == 8 || counter == 12)
{
System.out.println("" + br.read());
if (counter == 12)
break;
}
}
}
catch (IOException e)
{
System.out.println("Exception " + e);
}
finally
{
try
{
if (br != null)
{
br.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
Regarding the last question: According to this answer, Java 8 enables you to extract specific lines from a file. Examples are provided in that answer.
here you can find the the solution for reading a file according to the line no. This site is the best It contain this code in all the programming languages. And I have given you the java code.
https://www.rosettacode.org/wiki/Read_a_specific_line_from_a_file#Java
Related
I'm trying to find an object in a list from a text file
Example:
L;10;€10,50;83259875;YellowPaint
-H;U;30;€12,00;98123742;Hammer
G;U;80;€15,00;87589302;Seeds
By inserting 98123742 by input with scanner, i want to find that string.
I tried to do this:
private static void inputCode() throws IOException {
String code;
String line = null;
boolean retVal = false;
System.out.println("\ninsert code: ");
code = in.next();
try {
FileReader fileReader = new FileReader("SHOP.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] token = line.split(";");
if (token[0].equals(code) && token[1].equals(code)) {
retVal = true;
System.out.println(line);
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("impossible open the file " + fileName);
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
System.out.println(retVal);
}
How can i print "-H;U;30;€12,00;98123742;Hammer" inserting "98123742" (that is the code of the product) ?
Why are you splitting in the first place? For such a simple usecase, and with that line format, I'd go with
line.contains(";" + code);
Not much else to do.
This program is meant to see two files located in a particular folder and then merge those two files and create a third file which is does. From the third merged file it is then searching for a keyword such as "test", once it finds that key word it prints out the location and the line of the keyword which is what is somewhat doing. What is happening is when I run the program it stops after the finds the keyword the first time in a line but it will not continue to search that line. So if there is multiple keyword 'test' in the line it will only find the first one and spit back the position and line. I want it to print both or multiple keywords. I think it is because of the IndexOf logic which is causing the issue.
import com.sun.deploy.util.StringUtils;
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Concatenate {
public static void main(String[] args) {
String sourceFile1Path = "C:/Users/me/Desktop/test1.txt";
String sourceFile2Path = "C:/Users/me/Desktop/test2.txt";
String mergedFilePath = "C:/Users/me/Desktop/merged.txt";
File[] files = new File[2];
files[0] = new File(sourceFile1Path);
files[1] = new File(sourceFile2Path);
File mergedFile = new File(mergedFilePath);
mergeFiles(files, mergedFile);
stringSearch(args);
}
private static void mergeFiles(File[] files, File mergedFile) {
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, true);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void stringSearch(String args[]) {
try {
String stringSearch = "test";
BufferedReader bf = new BufferedReader(new FileReader("C:/Users/me/Desktop/merged.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file");
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
}
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
It's because you are searching for the word once per line in your while loop. Each iteration of the loop takes you to the next line of the file because you are calling bf.readLine(). Try something like the following. You may have to tweak it but this should get you close.
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
while(indexfound > -1)
{
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
indexfound = line.indexOf(stringSearch, indexfound);
}
}
public class Auto
{
public static void main(String [] args) {
// The name of the file to open.
System.out.print("\nPlease enter TextfileName.txt : ");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.next();
int counter = 0;
//Reading filename.text from code
System.out.println("\nReading '"+fileName+"' from Java Code.\n");
//Date and time stamp for the program.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.print("Todays date: "+dateFormat.format(date)+"\n\n\n");
// This will reference one line at a time
String line = null;
FileReader fileReader = null;
//-------------------------------------------------------TAB_1----------------------------------------------//
System.out.println("\t\t\t\t TAB_1[Date on]\n");
try {
// FileReader reads text files in the default encoding.
fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
counter++;
if(counter == 1 || counter == 3 || counter == 9)
{
// print out the lines above that are found in the text
System.out.println(line);
System.out.println("----------");
}
}
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
finally
{
if(fileReader != null){
// Always close files.
// BufferedReader.close();
}
}
some matcher would help, but i`m not sure how it works
}}
The one i have above is working but i want to also find a specific string anywhere in the text-file and print that line
Just use the contains method of the String class to check for occurances of a substring inside a string.
while((line = bufferedReader.readLine()) != null) {
if (line.contains("some string") {
System.out.println(line);
System.out.println("----------");
}
}
If you wish to check multiple substrings and not just one then you should create a String array of all the substrings you want to look for and loop through them.
First add the following line at the beggining of the class :
public static final String[] listOfStrings = new String[] { "substring 0", "sub string 1" , "substring 2" };
Replace the substrings with your own values.
Then, loop through them to find matches:
while((line = bufferedReader.readLine()) != null) {
for (String match : listOfStrings) {
if (line.contains(match)) {
System.out.println(line);
System.out.println("----------");
break; // No need to continue after the first match
}
}
}
I have a class which can read a file, modify it an write it to another file. The characters in the output are correct , the only problem is that the lines need to have a length of 12 chars.
How can I achieve this with my existing code?(I wrote a comment where in the code I want to do this)
My input file: http://gyazo.com/13fe791d24ef86e29ab6a6e89d0af609
The current output: http://gyazo.com/cc195c1d59a9d1fe3b4f2c54e71da8eb
The output I want : http://gyazo.com/04efcbb05c5d56b6e28972feb8c43fb8
String line;
StringBuilder buf = new StringBuilder();
public void readFile(){
BufferedReader reader = null;
try {
File file = new File("C:/Users/Sybren/Desktop/Invoertestbestand1.txt");
reader = new BufferedReader(new FileReader(file));
//String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
//buf.append(line);
processInput();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
};
}
}
public void processInput(){
buf.append(line);
if (buf.length()>7){
buf.append("-");
}
/* if a * is followed by * change them to a ! */
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
}
}
// get last character from stringbuilder and delete
buf.deleteCharAt(buf.length()-1);
/* start with a new line if the line length is bigger than 12 - how to do it? */
//???
}
public void writeFile() {
try {
String content = buf.toString();
File file = new File("C:/Users/Sybren/Desktop/uitvoer1.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}}
Would something along these lines help?
for (int i=13;i<buf.size();i+=13) {
buf.insert(i, '\n');
i++; // to account for the newline char just added
}
The numbers used may not be correct, either because of misunderstanding of the question or because it isn't tested.
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
}
}
There will be an java.lang.ArrayIndexOutOfBoundsException at the end of the loop when you you call index+1
I have a snippet of code that prints text from a file to a JTextArea called textArea.
Unfortunately the method I'm using goes line by line (not ideal) and so I have to append each line with a \n
This is fine for now but a new line is created at the end.
The code I have is as follows:
class menuOpen implements ActionListener {
public void actionPerformed(ActionEvent e)
{
try {
File filePath = new File("c:\\test.txt");
FileInputStream file = new FileInputStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(file));
String displayText;
while ((displayText = br.readLine()) != null) {
textArea.append(displayText + "\n");
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Can anyone help me get rid of that last line?
how about:
text.substring(0,text.lastIndexOf('\n'));
(...)
FileReader r= new FileReader(filePath);
StringBuilder b=new StringBuilder();
int n=0;
char array[]=new char[1024];
while((n=r.read(array))!=-1) b.append(array,0,n);
r.close();
String content=b.toString();
textArea.setText(content.substring(0,content.lengt()-1);
(...)
Another idea:
boolean firstLine = true;
while ((displayText = br.readLine()) != null) {
if (firstLine) {
firstLine = false;
} else {
textArea.append("\n");
}
textArea.append(displayText);
}
The idea is to append a line break before the new line to display, except for the first line of the file.
The easiest way is to not use BufferedReader.readLine(). For example:
BufferedReader in = new BufferedReader(new FileReader(filePath));
char[] buf = new char[4096];
for (int count = in.read(buf); count != -1; count = in.read(buf)) {
textArea.append(new String(buf, 0, count));
}
EDIT
I should have seen this before, but a much better way is to let the JTextArea read the file:
BufferedReader in = new BufferedReader(new FileReader(filePath));
textArea.read(in, null);
This will still read in the newline at the end, but it will normalize all the line endings in your text (see the javadocs for DefaultEditorKit for an explanation of how line endings are handled). So you can get rid of the trailing newline with something like this:
// line endings are normalized, will always be "\n" regardless of platform
if (textArea.getText().endsWith("\n")) {
Document doc = ta.getDocument();
doc.remove(doc.getLength() - 1, 1);
}
How about
if (textArea.length > 0) textArea.Text = textArea.Text.Substring(0 ,textArea.Text.Length - 1)
Apparently you want a newline between two lines, not after each line. This means you should have at least two lines:
if (d = br.readLine()) != null ) {
textArea.append(displayText);
while (d = br.readLine()) != null ) {
textArea.append( "\n" + displayText);
}
}
Of course, it looks more complex. That's because 'between' is more complex than 'after'.
In your loop:
while ((displayText = br.readLine()) != null) {
if (textArea.length() > 0)
textArea.append("\n");
textArea.append(displayText);
}
i.e. if there is already some text in your textarea, insert a newline.
Its quite easy.. You just need to tweak your code a bit.
String displayText = br.readLine();
textArea.append(displayText);
while ((displayText = br.readLine()) != null) {
textArea.append("\n" + displayText);
}
I believe this code produce your desired function at minimum cost.