Just try to get the line right in the while statement
try {
FileReader fr = new FileReader("Original.txt");
BufferedReader br = new BufferedReader(fr);
String strFullName;
while ((strFullName = br.readLine()) != null) {
int intSpaceLocation = strFullName.indexOf(" ");
String strLastName = strFullName.substring(0, intSpaceLocation);
String strFirstName = strFullName.substring(intSpaceLocation + 1);
System.out.println("First Name = " + strFirstName + " Last Name = " + strLastName);
}
br.close();
fr.close();
} catch (Exception e) {
}
I am trying to get each line from a file and trying to split it with a space, but it only does it for the first line
Output:
First Name = Todd Last Name = Jackson
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);
}
}
So I've been working on a program that will display the line number and the line itself of the searched text string. If I search dog, and I have lines in my text file that contain the word dog, those lines and line numbers should be shown. I also have created a method that counts the characters, words, and lines of a text file. However, the problem I am having is that whenever I run my program I don't get the line numbers with the lines of the searched text. I successfully get the text from the text file in the console and I successfully get the number of lines, words, etc.
Here's my written code, I am guessing it has to do something with the fact that I don't have a "return results;" statement, but I am not sure where to put it, and if I add it to the end of "+ characters + " characters. "" line by doing "+ results", it just gives me empty brackets.
Maybe I am doing something wrong? Perhaps something to do with closing the file and stream, not sure. Please help, I've tried moving stuff around but no luck.
public String words() {
try {
int words = 0;
int numbers = 0;
int lines = 1;
int characters = 0;
int total = 0;
String c = " ";
FileReader r = new FileReader(file1);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList<String> results = new ArrayList<String>();
t.resetSyntax();
t.wordChars('0', '9');
t.wordChars('A', 'Z');
t.wordChars('a', 'z');
t.whitespaceChars(0, ' ');
t.eolIsSignificant(true);
while (t.nextToken() != StreamTokenizer.TT_EOF) {
switch (t.ttype) {
case StreamTokenizer.TT_NUMBER:
numbers++;
break;
case StreamTokenizer.TT_WORD:
characters += t.sval.length();
words++;
break;
case StreamTokenizer.TT_EOL:
lines++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
br.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
String line = null;
while ((line = lnr.readLine()) != null) {
if (line.indexOf(word) >= 0) {
results.add(lnr.getLineNumber() + line);
}
}
r.close();
total = numbers + words;
lnr.close();
return file1.getName() + " has " + lines + " lines, "
+ total + " words, "
+ characters + " characters. ";
} catch (IOException e) {
display(e.toString(), "Error");
}
return " ";
}
Here's the main class if needed:
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
public class BasicFile {
File file1;
JFileChooser selection;
File file2 = new File(".", "Backup File");
public BasicFile() {
selection = new JFileChooser(".");
}
public void selectFile() {
int status = selection.showOpenDialog(null);
try {
if (status != JFileChooser.APPROVE_OPTION) {
throw new IOException();
}
file1 = selection.getSelectedFile();
if (!file1.exists()) {
throw new FileNotFoundException();
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File Not Found ", "Error", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
System.exit(0);
}
}
public void backupFile() throws FileNotFoundException {
DataInputStream in = null;
DataOutputStream out = null;
try {
in = new DataInputStream(new FileInputStream(file1));
out = new DataOutputStream(new FileOutputStream(file2));
try {
while (true) {
byte data = in.readByte();
out.writeByte(data);
}
} catch (EOFException e) {
JOptionPane.showMessageDialog(null, "File has been backed up!",
"Backup Complete!", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found ",
"Error", JOptionPane.INFORMATION_MESSAGE);
}
} finally {
try {
in.close();
out.close();
} catch (Exception e) {
display(e.toString(), "Error");
}
}
}
boolean exists() {
return file1.exists();
}
public String toString() {
return file1.getName() + "\n" + file1.getAbsolutePath() + "\n" + file1.length() + " bytes";
}
public String words() {
try {
int words = 0;
int numbers = 0;
int lines = 1;
int characters = 0;
int total = 0;
String c = " ";
FileReader r = new FileReader(file1);
LineNumberReader lnr = new LineNumberReader(r);
StreamTokenizer t = new StreamTokenizer(r);
ArrayList<String> results = new ArrayList<String>();
t.resetSyntax();
t.wordChars('0', '9');
t.wordChars('A', 'Z');
t.wordChars('a', 'z');
t.whitespaceChars(0, ' ');
t.eolIsSignificant(true);
while (t.nextToken() != StreamTokenizer.TT_EOF) {
switch (t.ttype) {
case StreamTokenizer.TT_NUMBER:
numbers++;
break;
case StreamTokenizer.TT_WORD:
characters += t.sval.length();
words++;
break;
case StreamTokenizer.TT_EOL:
lines++;
break;
case StreamTokenizer.TT_EOF:
break;
default:
}
}
FileInputStream fstream = new FileInputStream(file1);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
br.close();
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
String word = find;
String line = null;
while ((line = lnr.readLine()) != null) {
if (line.indexOf(word) >= 0) {
results.add(lnr.getLineNumber() + line);
}
}
r.close();
total = numbers + words;
lnr.close();
return file1.getName() + " has " + lines + " lines, "
+ total + " words, "
+ characters + " characters. ";
} catch (IOException e) {
display(e.toString(), "Error");
}
return " ";
}
void display(String msg, String s) {
JOptionPane.showMessageDialog(null, msg, s, JOptionPane.ERROR_MESSAGE);
}
}
You are nearly there.
reinitialize your FileReader and LineNumberReader before your while ((line = lnr.readLine()) != null) loop.
Then your ArrayList will be full of the #String that I think you desire.
what you can do is start counting the lines in the file (starting by 0), then increase by 1 every time a new line is found.. then check if the string you want to find is contained in the line, then print the number of the line where the keyword is found (using the contains() function in Java). I assumed you want to check for both upper and lower case, if you don't want that then simply remove the toLowerCase() ! So, read the file properly in Java:
long lineNumber = 0;
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String line = myReader.readLine();
while(line != null){
lineNumber++;
System.out.println("The line I am now examining is : " + line + " and the line number is : " + lineNumber);
if line.toLowerCase().contains(word.toLowerCase()) {
System.out.println("Line number: " + lineNumber + " contains keyword : " + word);
line = myReader.readLine();
}
The problem is that I have a windows excel exported CSV with Swedish letters åäöÅÄÖ. When I upload them and convert to string I get those letters completely messed up. The server is tomcat7 on linux. It's set to use iso-8859-1.
I have tried different byte[] conversions but none seem to work. I have removed all conversions I have tried from this code.
public void run(InputStreamReader is) {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
try {
br = new BufferedReader(is);
while ((line = br.readLine()) != null) {
// use comma as separator
String[] playerInfo = line.split(cvsSplitBy);
System.out.println("Förnamn: " + playerInfo[0]
+ "Efternamn: " + playerInfo[1]
+ "Klubb= " + playerInfo[7]
+ " , datum=" + playerInfo[10]
+ " , Total= " + playerInfo[14]
+ " , serier= " + playerInfo[15]);
saveInfo(playerInfo);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}