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
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 am trying to duplicate the original into a new file. In the new file I want the exact same things as the original BUT no blank lines.
Note: I looked at other posts and tried with no success.
Currently:
1
2
3
How I want it to be: -- no blank lines
1
2
3
Here is my code so far:
inputFileName = "x.txt";
outputFileName = "y.txt";
inputFile = new BufferedReader(new FileReader(inputFileName));
outputFile = new PrintWriter(new FileWriter(outputFileName));
String lineOfText = inputFile.readLine();
while(lineOfText != null)
{
if (lineOfText.isEmpty())
{
outputFile.print("null");
}
outputFile.println(lineOfText);
lineOfText = inputFile.readLine();
}
inputFile.close();
outputFile.close();
}
Thank you for all who can possibly help. I assumed that print("null") would print out 'nothing' but it indeed prints out null, I do not know how to print out 'nothing'.
You need to skip the println in case the line is empty:
while(lineOfText != null)
{
if (!lineOfText.isEmpty()) {
outputFile.println(lineOfText);
}
lineOfText = inputFile.readLine();
}
You're on the right track, but this
while(lineOfText != null)
{
if (lineOfText.isEmpty())
{
outputFile.print("null");
}
outputFile.println(lineOfText);
lineOfText = inputFile.readLine();
}
shouldn't be writing null on empty lines. I think you wanted something like
while(lineOfText != null)
{
if (!lineOfText.isEmpty())
{
outputFile.println(lineOfText);
}
lineOfText = inputFile.readLine();
}
Also, I suggest you use a try-with-resources Statement instead of manually managing your close(s). It's probably a good idea to trim (as suggested in the comments) before your test, and you can simplify your loop and you should limit variable visibility. All together like,
String inputFileName = "x.txt";
String outputFileName = "y.txt";
try (BufferedReader inputFile = new BufferedReader(new FileReader(inputFileName));
PrintWriter outputFile = new PrintWriter(new FileWriter(outputFileName))) {
String lineOfText;
while ((lineOfText = inputFile.readLine()) != null) {
lineOfText = lineOfText.trim();
if (!lineOfText.isEmpty()) {
outputFile.println(lineOfText);
}
}
}
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data1.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
I was using my code to do a replace line feature. It was working initially but suddenly my new file became blank and the code did not bring me back to the AdminMenu(), as well as the file not being renamed. There is also another issue where if I use "\r\n" there will be a blank line on top of my file which I am trying to remove. I tried using \n after totalChips, but it doesn't seem to work. I could use some advice on this.
output
<Blank File>
expected output
Line1|password|500
Line2|password|600
//ModifiedLine can be either line based on UserName
codes are below
public static void AddChips() {
File oldFileName = new File("players.dat");
File tmpFileName = new File("newplayers.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN))
line = Username + "|" + Password + "|" + totalChips;
bw.write("\r\n"+line);
}
bw.close();
br.close();
oldFileName.delete();
tmpFileName.renameTo(oldFileName);
AdminMenu();
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
new Error
java.lang.ArrayIndexOutOfBoundsException: 1
at testcode.AddChips(testcode.java:53)
at testcode.main(testcode.java:11)
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.
How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.