I have been trying to compare the input file with the database file. The code compares the files and outputs the words from the input file(test.txt) that are present in the database file(db.txt). But however I am not getting the last word from the input file in the output.
test.txt contains:
There is a book on the table
db.txt contains:
book
the
table
Thus here I am not getting table in the output.
public static void main(String[] args) {
try {
File file = new File("G:\\Project\\test.txt");
File file2 = new File("G:\\Project\\db.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
StringTokenizer st = new StringTokenizer(stringBuffer.toString()," ");
while (st.hasMoreTokens())
{
String word=st.nextToken();
BufferedReader br = new BufferedReader(new FileReader(file2));
String lin;
while((lin=br.readLine())!=null){
{ if(word.equalsIgnoreCase(lin))
System.out.println(word);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Output received:
book
the
What is it that I am doing wrong here?
You are appending newline character to stringbuffer and that is causing this issue.
Remove below line from your code and try, it will work.
stringBuffer.append("\n");
Related
I am new to java and working on file operations. I have this input and modify text files as follows:
input.txt: contains id,firstname,lastname
1000:Mark,Peters,3.9
modify.txt: contains id,oldvalue:newvalue
1000,Mark:John
I am supposed to search the id and make the updations accordingly. So in modify.txt file I have an id and old value which is to be replaced with new value in the input.txt
So after modification, my input.txt line output should be printed as:
1000:John,Peters,3.9
I have written the following code, but I am not sure how to proceed with updations. However, I have managed to read the files and split it and get the id.
public static void main(String[] args) {
try {
BufferedReader file1 = new BufferedReader(new FileReader(new File("src/input.txt")));
BufferedReader file2 = new BufferedReader(new FileReader(new File("src/modify.txt")));
String str1 = file1.readLine();
String input[] = str1.split(":");
int id1 = Integer.parseInt(input[0]);
System.out.println(str1);
System.out.println(id1);
String str2 = file2.readLine();
String modify[] = str2.split(",");
int id2 = Integer.parseInt(modify[0]);
System.out.println(str2);
System.out.println(id2);
file1.close();
file2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Can anyone help me with this? Thanks. Appreciate your help.
You can read the line in modify.txt file and split the line using regex [,:]. It will split the line into separate parts like id, firstName and lastName etc.
After read the each line in input.txt file and and split the each line using the regex [,:]. And compare the first element in the list with element in the list created from modify.txt file. if the element is equals replace the line with the new data from list created from modify.txt file.
public static void main(String[] args) {
try {
BufferedReader f1 = new BufferedReader(new FileReader(new File("src/input.txt")));
BufferedReader f2 = new BufferedReader(new FileReader(new File("src/modify.txt")));
String regex = "[,:]";
StringBuffer inputBuffer = new StringBuffer();
String line;
String[] newLine = f2.readLine().split(regex);
while ((line = f1.readLine()) != null) {
String[] data = line.split(regex);
if (data[0].equals(newLine[0])) {
line = line.replace(newLine[1], newLine[2]);
}
inputBuffer.append(line);
inputBuffer.append(System.lineSeparator());
}
f1.close();
f2.close();
FileOutputStream fileOut = new FileOutputStream("src/input.txt");
fileOut.write(inputBuffer.toString().getBytes());
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm new to coding in java. Can anyone help me with my codes? I'm currently making a program where you input a string in a jTextArea, and if the input word(s) matches the one in the text file then it will then do something.
For example: I input the word 'Hey' then it will print something like "Hello" when the input word matches from the text file.
I hope you understand what I mean.
Here's my code:
String line;
String yo;
yo = jTextArea2.getText();
try (
InputStream fis = new FileInputStream("readme.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
)
{
while ((line = br.readLine()) != null) {
if (yo.equalsIgnoreCase(line)) {
System.out.print("Hello");
}
}
} catch (IOException ex) {
Logger.getLogger(ArfArf.class.getName()).log(Level.SEVERE, null, ex);
}
You can not use equals for line because a line contain many words. You have to modify it to search the index of the word in a line.
try (InputStream fis = new FileInputStream("readme.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
line = line.toLowerCase();
yo = yo.toLowerCase();
if (line.indexOf(yo) != -1) {
System.out.print("Hello");
}
line = br.readLine();
}
} catch (IOException ex) {
}
since you are new in java , I would suggest you to take some time to study java 8 which enable to write more clean codes. below is the solution write in java 8, hope can give a kind of help
String yo = jTextArea2.getText();
//read file into stream,
try (java.util.stream.Stream<String> stream = Files.lines(Paths.get("readme.txt"))) {
List<String> matchLines = stream.filter((line) -> line.indexOf(yo) > -1).collect(Collectors.toList()); // find all the lines contain the text
matchLines.forEach(System.out::println); // print out all the lines contain yo
} catch (IOException e) {
e.printStackTrace();
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordFinder {
public static void main(String[] args) throws FileNotFoundException {
String yo = "some word";
Scanner scanner = new Scanner(new File("input.txt")); // path to file
while (scanner.hasNextLine()) {
if (scanner.nextLine().contains(yo)) { // check if line has your finding word
System.out.println("Hello");
}
}
}
}
I really new to Java so I'm having some trouble figuring this out. So basically I have a text file that looks like this:
1:John:false
2:Bob:false
3:Audrey:false
How can I create an ArrayList from the text file for each line?
Read from a file and add each line into arrayList. See the code for example.
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(<your_file_path>)))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
arr.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
While the answer above me works, here's another way to do it. Make sure to import java.util.Scanner.
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner("YOURFILE.txt");
while(scan.hasNextLine()){
list.add(scan.nextLine());
}
scan.close();
}
If you know how to read a file line by line, either by using Scanner or by using BufferedReader then reading a text file into ArrayList is not difficult for you. All you need to do is read each line and store that into ArrayList, as shown in following example:
BufferedReader bufReader = new BufferedReader(new
FileReader("file.txt"));
ArrayList<String> listOfLines = new ArrayList<>);
String line = bufReader.readLine(); while (line != null)
{
listOfLines.add(line);
line = bufReader.readLine();
}
bufReader.close();
Just remember to close the BufferedReader once you are done to prevent resource leak, as you don't have try-with-resource statement
This will be help to you.
List<String> list = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("list.txt"));
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
reader.close();
Then you can access those elements in the arraylist.
java 8 lets you do this
String fileName = "c://lines.txt";
List<String> list = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
list = stream
.map(String::toUpperCase)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
list.forEach(System.out::println);
I've been looking around on the Internet trying to figure out which could be the best way to read from text files which are not very long (the use case here involves small OpenGL shaders). I ended up with this:
private static String load(final String path)
{
String text = null;
try
{
final FileReader fileReader = new FileReader(path);
fileReader.read(CharBuffer.wrap(text));
// ...
}
catch(IOException e)
{
e.printStackTrace();
}
return text;
}
In which cases could this chunk of code result in inefficiencies? Is that CharBuffer.wrap(text) a good thing?
If you want to read the file line by line:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
If you want to read the complete file in one go:
String text=new String(Files.readAllBytes(...)) or Files.readAllLines(...)
I would usually just roll like this. The CharBuffer.wrap(text) thing seems to only get you a single character ... File Reader docs
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String s;
while((s = br.readLine()) != null) {
sb.append(s);
}
fr.close();
return sb.toString();
I want to write a simple java program to read in a text file and then write out a new file whenever a blank line is detected. I have seen examples for reading in files but I don't know how to detect the blank line and output multiple text files.
fileIn.txt:
line1
line2
line3
fileOut1.txt:
line1
line2
fileOut2.txt:
line3
Just in case your file has special characters, maybe you should specify the encoding.
FileInputStream inputStream = new FileInputStream(new File("fileIn.txt"));
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
int n = 0;
PrintWriter out = new PrintWriter("fileOut" + ++n + ".txt", "UTF-8");
for (String line;(line = reader.readLine()) != null;) {
if (line.trim().isEmpty()) {
out.flush();
out.close();
out = new PrintWriter("file" + ++n + ".txt", "UTF-8");
} else {
out.println(line);
}
}
out.flush();
out.close();
reader.close();
streamReader.close();
inputStream.close();
I don't know how to detect the blank line..
if (line.trim().length==0) { // perform 'new File' behavior
.. and output multiple text files.
Do what is done for a single file, in a loop.
You can detect an empty string to find out if a line is blank or not. For example:
if(str!=null && str.trim().length()==0)
Or you can do (if using JDK 1.6 or later)
if(str!=null && str.isEmpty())
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
// Line is empty
}
}
The above code snippet can be used to detect if the line is empty and at that point you can create FileWriter to write to new file.
Something like this should do :
public static void main(String[] args) throws Exception {
writeToMultipleFiles("src/main/resources/fileIn.txt", "src/main/resources/fileOut.txt");
}
private static void writeToMultipleFiles(String fileIn, String fileOut) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileIn))));
String line;
int counter = 0;
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileOut))));
while((line=br.readLine())!=null){
if(line.trim().length()!=0){
wr.write(line);
wr.write("\n");
}else{
wr.close();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut + counter)));
wr.write(line);
wr.write("\n");
}
counter++;
}
wr.close();
}