The "Number of Lines = 4" shows it's reading all 4 lines of the text file.
But then "Line read = null". I don't know why the readLine() method is not reading the first line.
import java.io.*;
public class TestLineRead {
public static void main (String[] args)
{
try
{
File tmpFileIn = new File("C:/Java/Employees.txt");
BufferedReader br = new BufferedReader (new InputStreamReader(
new FileInputStream(tmpFileIn)));
LineNumberReader lnr = new LineNumberReader(br);
int numOfLines = 0;
while (lnr.readLine() != null) {
numOfLines++;
}
String str = null;
System.out.println("Number of lines = " + numOfLines);
str = br.readLine();
System.out.println("Line read = " + str);
br.close();
}
catch (IOException e) { System.out.println("error: " + e.getMessage()); }
} // close main
} // close Class
I don't know why the readLine() method is not reading the first line.
It did, when you were counting lines.
This
while (lnr.readLine() != null) {
numOfLines++;
}
consumes lines. It returns null when there are no more lines left.
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.
I know that there are already some posts about this problem but I don't understand them.
My problem is that I want to find a line in a txt document with a name and I then want to change the next line to the content of a string.
This is what I tried:
public void saveDocument(String name) {
String documentToSave = textArea1.getText();
File file = new File("documents.txt");
Scanner scanner;
BufferedWriter bw;
try {
scanner = new Scanner(file);
bw = new BufferedWriter(new FileWriter(file));
while(scanner.hasNextLine()) {
if(scanner.nextLine().equals(name)) {
if(scanner.hasNextLine()) bw.write(scanner.nextLine() + "\n");
bw.write(documentToSave + "\n");
if(scanner.hasNextLine()) scanner.nextLine();
}
if(scanner.hasNextLine()) bw.write(scanner.nextLine() + "\n");
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
May be you try it this way: read your file and keep each line in a list of strings and if you find the name you are looking for replace the next line you read. And then write the strings from that list back to your file. Example:
public class NewClass {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list = readFile("uzochi");
writeToFile(list);
}
public static List<String> readFile(String name){
List<String> list = new ArrayList<String>();
try {
FileReader reader = new FileReader("C:\\users\\uzochi\\desktop\\txt.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
boolean nameFound = false;
while ((line = bufferedReader.readLine()) != null) {
if(line.equalsIgnoreCase(name)){
nameFound = true;
System.out.println("searched name: "+line);
}
if(nameFound){
list.add(line);
line = bufferedReader.readLine();
System.out.println("line to replace: " + line);
line = "another string";
System.out.println("replaced line: "+line);
list.add(line);
nameFound = false;
}
else{
list.add(line);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void writeToFile(List<String> list){
try {
FileWriter writer = new FileWriter("C:\\users\\uzochi\\desktop\\txt.txt", false);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
for(String s: list){
bufferedWriter.write(s);
bufferedWriter.newLine();
}
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
txt.txt
hallo
hello
hola
uzochi
world
java
print
This code should read the entire file and replace the line with the name.
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.equals(name)) {
bw.write(documentToSave + "\n");
} else {
bw.write(line + "\n");
}
}
This program will replace the line after a given line. It needs some more work from us, for example if we can define expected i/o and usage. Now it reads from a file and reeplaces a line, but maybe you want to use the line number instead of the line contents to mark which line to replace.
import java.io.*;
public class FileLineReplace {
public static void replaceSelected(String replaceWith, String type) {
try {
String input2 = "";
boolean replace = false;
String input = "";
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
for (String line;
(line = br.readLine()) != null;) {
// process the line.
System.out.println(line); // check that it's inputted right
if (replace) {
line = "*** REPLACED ***";
replace = false;
}
if (line.indexOf("replaceNextLine") > -1) {
replace = true;
}
input2 = input2 += (line + "\n");
}
// line is not visible here.
}
// check if the new input is right
System.out.println("----------------------------------" + '\n' + input2);
// write the new String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("data.txt");
fileOut.write(input2.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
e.printStackTrace();
}
}
public static void main(String[] args) {
replaceSelected("1 adam 20 M", "foobar");
}
}
If you run the code, it will replace next line after a line which is "replaceNextLine":
$ java FileLineReplace
asd
zxc
xcv
replaceNextLine
wer
qwe
----------------------------------
asd
zxc
xcv
replaceNextLine
*** REPLACED ***
qwe
My test file is (was)
asd
zxc
xcv
replaceNextLine
wer
qwe
After I run the program, the file looks like this and the line after the specified line is replaced.
asd
zxc
xcv
replaceNextLine
*** REPLACED ***
qwe
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);
}
}
I am trying to design two different methods for a Java application. The first method will pass in a string of the name of a file, and return the text of a text file as a string. The second method will pass in the name of a file and the text, and create a new text file and output the string into the file.
Currently my code works without the methods, but I am trying to design it with a separation of concerns and low coupling. I am trying to modify it so I can just call a method to output any sort of data I have in a string to a text file.
Here is my code without the methods:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileCopier {
public static void main(String[] args) {
//What file should be input for reading?
String inputFile = askForInput("Please enter the name of the file to be read in: ");
//What file should be created to display output ?
String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
//Check to make sure we got the names
System.out.println("inputFile: " + inputFile + " outputFile: " + outputFile);
// Variables to read and write the files
//Call the readTextFile method to read text file into string data
String line = null;
String total = null;
BufferedReader input = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
//Check to make sure we got the text files data
System.out.println("The total string says: \n" + total);
//Call the reverseWords method to switch 'Hello' with 'World'
String info = reverseWords(total);
//Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + info);
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" +
inputFile + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
public static String reverseWords(String sentence) {
String[] parts = sentence.trim().split("\\s+");
StringBuilder builder = new StringBuilder();
builder.append(parts[parts.length - 1]);
for (int i = parts.length - 2; i >= 0; --i) {
builder.append(" ").append(parts[i]);
}
return builder.toString();
}
public static String askForInput(String question) {
System.out.println(question);
Scanner in = new Scanner(System.in);
String inputFile = in.nextLine();
return inputFile;
}
}
When creating a method for each of the "read" and "write" portions of my code, I constantly get errors that I assume are from the exception handling. Any thoughts on how to separate code that has exceptions involved?
Think in terms of single responsibility. You have two distinct operations that need to happen: reading and writing.
Let's start with reading. What you're doing right now to read the file surmises these lines:
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
Move that to a method.
private static String readFile(String inputFile) throws IOException {
BufferedReader input;
String total;
String line;// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
return total;
}
Here's what we did:
We have a variable total which is used elsewhere in the program, so that usage has to be preserved. We're returning String and will declare total = readFile(inputFile); on the outside.
We've changed nothing. This code will run the same way as it did without the method.
Now, if we want to move the writing functionality, which is:
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
...we just do.
private static void writeFile(String outputFile, String info) throws IOException {
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
}
Again, nothing's changed on this method. We don't have any other usages of any of the variables in here to worry about, so we can directly bring it across.
All said, that try block looks a bit anemic:
try {
total = readFile(inputFile);
//Check to make sure we got the text files data
System.out.println("The total string says: \n" + total);
//Call the reverseWords method to switch 'Hello' with 'World'
String info = reverseWords(total);
//Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + info);
writeFile(outputFile, info);
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" +
inputFile + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
...which is a good thing.
I am not sure what are you asking about but try to create your own Exceptions and make your methods throw them like this
package com.qmic.test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileCopier {
public static void main(String[] args) {
// What file should be input for reading?
String inputFile = askForInput("Please enter the name of the file to be read in: ");
// What file should be created to display output ?
String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
// Check to make sure we got the names
System.out.println("inputFile: " + inputFile + " outputFile: "
+ outputFile);
// Variables to read and write the files
// Call the readTextFile method to read text file into string data
String line = null;
String total = null;
BufferedReader input = null;
try {
String readData = readFileContents(inputFile);
// Check to make sure we got the text files data
System.out.println("The total string says: \n" + readData);
// Call the reverseWords method to switch 'Hello' with 'World'
String reversedContents = reverseWords(readData);
writeToFile(outputFile, reversedContents);
} catch (ReadException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
} catch (WriteException ex) {
System.out.println("Error Writing file '" + outputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
public static String reverseWords(String sentence) {
String[] parts = sentence.trim().split("\\s+");
StringBuilder builder = new StringBuilder();
builder.append(parts[parts.length - 1]);
for (int i = parts.length - 2; i >= 0; --i) {
builder.append(" ").append(parts[i]);
}
return builder.toString();
}
public static String askForInput(String question) {
System.out.println(question);
Scanner in = new Scanner(System.in);
String inputFile = in.nextLine();
return inputFile;
}
public static void writeToFile(String fileName, String data)
throws WriteException {
BufferedWriter output = null;
try {
// Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + data);
File file = new File(fileName);
output = new BufferedWriter(new FileWriter(file));
output.write(data);
System.out.println("The output file: " + fileName
+ " has been written.");
}catch(IOException e){
throw new WriteException();
}finally{
try {
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String readFileContents(String fileName) throws ReadException {
// FileReader reads text files in the default encoding.
BufferedReader input = null;
String line = null;
String total = null;
try {
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
} catch (IOException e) {
throw new ReadException();
}finally{
//This is ugly code, if you are using java 7 you have extra option to better this
try {
input.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return total;
}
}
//make me public and move me to a separate file
class WriteException extends IOException {
}
//make me public and move me to a separate file
class ReadException extends IOException {
}
My goal is that I wish to read from a file with the name "input.txt", which has 10 lines of text, and then write 5 lines from the original into two other files with the names "test1.txt" and "test2.txt". I'm using the following code, but it is not working - please help me.
import java.util.Scanner;
import java.io.*;
public class main {
public static void main (String args[]) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader (new FileReader("bin/input.txt"));
File file = new File("bin/test2.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter("bin/test.txt"));
Scanner sc = new Scanner (br);
int i = 0;
while (sc.hasNextLine()){
sc.nextLine();
i++;
System.out.print(i);
int n = (i+1)/2;
System.out.print("\n"+n);
writer.write(sc.nextLine().toString());
writer.newLine();
if (n==5){
writer.close();
}
}
if (sc != null){
sc.close();
}
}
}
this will read from single file and splitting content into two file.
int count = 0;
BufferedReader br = null;
FileWriter fileWriter1 = new FileWriter("G:\\test1.txt");
FileWriter fileWriter2 = new FileWriter("G:\\test2.txt");
try {
String currentLine;
br = new BufferedReader(new FileReader("G:\\input.txt"));
while ((currentLine = br.readLine()) != null) {
count++;
if (count <= 5) {
fileWriter1.write(currentLine + "\n");
} else {
fileWriter2.write(currentLine + "\n");
}
}
} finally {
if (br != null) {
br.close();
}
fileWriter1.close();
fileWriter2.close();
}
Create two BufferedWriter instead of one with two files and then follow the below procedure:
count <- 0
while scanner hasNextLine
do
string line <- scanner's next Line
if (count > 4) {
writer2.write line
} else {
writer1.write line
}
count <- count + 1
done
finally close all three resources.