Writing in a new text file - java

I read a file and create a new file that copies some part of it, removes some lines and replaces them with others. The input arraystring raw is of type [Aaa,Bbb,Ccc,..] and is used to replace part of the line.
In the new file, the non edited parts are printed properly, but the edited parts are printed this way. 1st one is printed, 2nd one not, 3rd yes, 4th no,5th yes... It looks like when I edit a line I erase the one below too. I tried removing out.write("\n") or scanner.nextLine() , but it didnt work either. Any ideas what could i try? Thanks in advance
For example:
OLD TEXT:
.....
LINE 6 / contains j(ac)
LINE 7 / contains i(ac)
LINE 8 / contains k(ac)
LINE 9 / contains mp(ac)
LINE 10 /contains bp(ac)
.....
NEW TEXT (NEW FILE):
.....
LINE NEW6
LINE NEW7
LINE NEW8
LINE NEW9
LINE NEW10
.....
public static void main(String[] args) {
new class();
class.query();
File file = new File("file");
File filenew = new File("file");
try {
PrintWriter out = new PrintWriter(new FileWriter(filenew, true));
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("j(ac)")) {
String newline = line.replaceAll("/.*?/", "/"+raw1+"/");
scanner.nextLine();
out.write(newline);
out.write("\n");
} else if (line.contains("i(ac)")) {
String newline = line.replaceAll("/.*?/", "/"+raw2+"/");
scanner.nextLine();
out.write(newline);
out.write("\n");
} else if (line.contains("k(ac)")) {
String newline = line.replaceAll("/.*?/", "/"+raw3+"/");
scanner.nextLine();
out.write(newline);
out.write("\n");
}else if (line.contains("mp(k)")) {
String newline = line.replaceAll("/.*?/", "/"+raw4+"/");
scanner.nextLine();
out.write(newline);
out.write("\n");
}else if (line.contains("bp(k)")) {
String newline = line.replaceAll("/.*?/", "/"+raw5+"/");
scanner.nextLine();
out.write(newline);
out.write("\n");
} else{
out.write(line);
out.write("\n");
}
}
out.flush();
out.close();
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

This is how it suppose to go from the information you provided in your comment.
Its line.contains that shows when i want to edit and which line.
That line that contains"" is the one I want to replace.
And all ifs I include should be used and printed.
String line;
while (scanner.hasNextLine()) {
// Get the line
line = scanner.nextLine();
// if line contains xxx then replace
if (line.contains("j(ac)")) {
line = line.replaceAll("/.*?/", "/"+raw1+"/");
} else if (line.contains("i(ac)")) {
line = line.replaceAll("/.*?/", "/"+raw2+"/");
} else if (line.contains("k(ac)")) {
line = line.replaceAll("/.*?/", "/"+raw3+"/");
}else if (line.contains("mp(k)")) {
line = line.replaceAll("/.*?/", "/"+raw4+"/");
}else if (line.contains("bp(k)")) {
line = line.replaceAll("/.*?/", "/"+raw5+"/");
}
// Write the line with replaced items
out.write(line);
out.write("\n");
}
Now what your code doing:
while (scanner.hasNextLine()) {
// get the line (very first line) and store that in "line"
String line = scanner.nextLine();
// check if line contains "j(ac)"
if (line.contains("j(ac)")) {
// if "line" contains replace everything and save it to "newline"
String newline = line.replaceAll("/.*?/", "/"+raw1+"/");
// get next line getting used for nothing (second line stored nowhere)
scanner.nextLine();
// write the newline to output file.
out.write(newline);
out.write("\n");
}
// some more if else blocks executing same patterns explained above
else{
// if nothing contains in "line" then write to output file
out.write(line);
out.write("\n");
}
}

Related

How read data from file that is separated by a blank line in Java

For example I have a file "input.txt" :
This is the
first data
This is the second
data
This is the last data
on the last line
And I want to store this data in a ArrayList in this form:
[This is the first data, This is the second data, This is the last data on the last line]
Note: Every data in file is separated by a blank line. How to skip this blank line?
I try this code but it don't work right:
List<String> list = new ArrayList<>();
File file = new File("input.txt");
StringBuilder stringBuilder = new StringBuilder();
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
String line = in.nextLine();
if (!line.trim().isEmpty())
stringBuilder.append(line).append(" ");
else {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
}
} catch (FileNotFoundException e) {
System.out.println("Not found file: " + file);
}
Blank lines are not really blank. There are end-of-line character(s) involved the terminate each line. An apparent empty line means you have a pair of end-of-line character(s) abutting.
Search for that pair, and break your inputs when found. For example, using something like String::split.
For example, suppose we have a file with the words this and that.
this
that
Let's visualize this file, showing the LINE FEED (LF) character (Unicode code point 10 decimal) used to terminate each line as <LF>.
this<LF>
<LF>
that<LF>
To the computer, there are no “lines”, so the text appears to Java like this:
this<LF><LF>that<LF>
You can more clearly now notice how pairs of LINE FEED (LF) characters delimit each line. Search for the instances of that pairing to parse your text.
You are actually almost there. What you missed is that the last 2 lines need to be handled differently, as there is NO empty-string line at the bottom of the file.
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
String line = in.nextLine();
//System.out.println(line);
if (!line.trim().isEmpty())
stringBuilder.append(line).append(" ");
else { //this is where new line happens -> store the combined string to arrayList
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
}
//Below is to handle the last line, as after the last line there is NO empty line
if (stringBuilder.length() != 0) {
list.add(stringBuilder.toString());
} //end if
for (int i=0; i< list.size(); i++) {
System.out.println(list.get(i));
} //end for
} catch (FileNotFoundException e) {
System.out.println("Not found file: " + file);
}
Output of above:
This is the first data
This is the second data
This is the last data on the last line
I added an if codition right after the while loop in your code and it worked,
List<String> list = new ArrayList<>();
File file = new File("input.txt");
StringBuilder stringBuilder = new StringBuilder();
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
String line = in.nextLine();
if (!line.trim().isEmpty()) {
stringBuilder.append(line).append(" ");
}
else {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
}
if (stringBuilder.toString().length() != 0) {
list.add(stringBuilder.toString());
}
} catch (FileNotFoundException e) {
System.out.println("Not found file: " + file);
}
System.out.println(list.toString());
I got the below output
[This is the first data , This is the second data , This is the last data on the last line ]

How to detect line feed in between two Strings or int using scanner?

Question:
I have this set of number in a .txt document, I want to use java.util.Scanner to detect the line feed in between 123, 456, and 789, print out the numbers in between the line feeds, is there any way to do so?
1 2 3
// \n here
4 5 6
// \n here
7 8 9
Output:
456
===========================================================================
Solutions that I tried:
(1) I tried using hasNextLine() method, however, it seems like hasNextLine() will tell me are there tokens in the next line and return a boolean instead of telling me is there \n. if (scan.hasNextLine()) { \\ do something }
(2) I also tried using: (However, using such condition will say "Syntax error on token 'Invalid Character'")
Scanner scan = new Scanner(new File("test.txt"));
// create int[] nums
while (scan.hasNext()) {
String temp = scan.next();
if (temp == \n) {
// nums.add(); something like this
}
}
System.out.print(nums); // something like this
I am thinking using \n as delimiters
ps. I did google and most of the results tell me to use .hasNextLine(), but I want it to identify a line feed (\n)
Scanner scans the next element by using new-line or whitespace as a delimiter by default. To let it read the whole content use scan.useDelimiter("\\Z").
Scanner scan = new Scanner(new File("test.txt"));
scan.useDelimiter("\\Z");
final String content = scan.next(); // content: "1 2 3\r\n\r\n4 5 6"
int index = 0;
System.out.println("Index of \\n");
while (index != -1) {
index = content.indexOf("\n", index);
if (index != -1) {
System.out.println(index);
// Or do whatever you wish
index++;
}
}
Output:
Index of \n
5
7
I'm not sure I understand 100% your question. So I'm assuming your file always will have 2 lines separated by ONLY ONE new line(\n). If I'm wrong please tell it.
String charsAfterNewLine = null;
//try-catch block with resources
//Scanner need to be closed (scan.close()) after finish with it
//this kind of block will do `scan.close()` automatically
try(Scanner scan = new Scanner(new File("test.txt"))){
//consume(skip) first line
if(scan.hasNextLine()){
scan.nextLine();
}else{
throw new Exception("File is empty");
}
//get second line
if(scan.hasNextLine()){
charsAfterNewLine = scan.nextLine();
}else{
throw new Exception("Missing second line");
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println("charsAfterNewLine: " + charsAfterNewLine);
If you want simple way, without try-catch:
String charsAfterNewLine = null;
//throws FileNotFoundException
Scanner scan = new Scanner(new File("test.txt"));
if(scan.hasNextLine()){
//consume(skip) first line
scan.nextLine();
if(scan.hasNextLine()){
//get second line
charsAfterNewLine = scan.nextLine();
}else{
System.out.println("Missing second line");
}
}else{
System.out.println("File is empty");
}
scan.close();
System.out.println("charsAfterNewLine: " + charsAfterNewLine);
Results(for both):
Input:
(empty file)
Output:
File is empty
charsAfterNewLine: null
-----
Input:
1 2 3 4 5 6
Output:
Missing second line
charsAfterNewLine: null
-----
Input:
1 2 3\n4 5 6
Output:
charsAfterNewLine: 4 5 6
while (scanner.hasNext()) {
String data = scanner.nextLine();
System.out.println("Data: " + data);
if (data.isEmpty()) {
System.out.println("Found it");
break;
}
}

Java letter replacement in file

So I done this so far, my program works for example turning numbers 123... into letters like abc...
But my problem is I can't make it work with special characters like : č, ć, đ. Problem is when I run it with special characters my file just get deleted.
edit: forgot to mention im working with .srt files , adding utf-8 in scanner worked for txt files, but when i tryed with .srt it just delete full contect from file.
The code:
LinkedList<String> lines = new LinkedList<String>();
// Opening the file
Scanner input = new Scanner(new File("input.srt"), "UTF-8");
while (input.hasNextLine()) {
String line = input.nextLine();
lines.add(replaceLetters(line));
}
input.close();
// Saving the new edited version file
PrintWriter writer = new PrintWriter("input.srt", "UTF-8");
for (String line: lines) {
writer.println(line);
}
writer.close();
The replace method:
public static String replaceLetters(String orig) {
String fixed = "";
// Go through each letter and replace with new letter
for (int i = 0; i < orig.length(); i++) {
// Get the letter
String chr = orig.substring(i, i + 1);
// Replace letter if nessesary
if (chr.equals("a")) {
chr = "1";
} else if (chr.equals("b")) {
chr = "2";
} else if (chr.equals("c")) {
chr = "3";
}
// Add the new letter to the end of fixed
fixed += chr;
}
return fixed;
}
Turn your
Scanner input = new Scanner(new File("input.txt"));
into
Scanner input = new Scanner(new File("input.txt"), "UTF-8");
You save in UTF-8, but read in a default charset.
Also, next time, use try-catch statements properly and include them in your post.

How to search a String Backup = True in a text file

There is a space between before and after = ...
( Backup = True )------ is a String to search(Even space is there between =)
File file = new File(
"D:\\Users\\kbaswa\\Desktop\\New folder\\MAINTENANCE-20150708.log.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.next();
lineNum++;
String name="Backup = True";
if (line.contains(name)) {
System.out.println("I found "+name+ " in file " +file.getName());
break;
}
else{
System.out.println("I didnt found it");
}
}
}
Scanner.next() returns the next complete token, so it will be returning something like Backup, then = next time round the loop, then true next time.
Use Scanner.nextLine() to get the entire line in one go.
scanner.nextLine() would solve your problem.
If you want to stick with scanner.next() you can define a delimiter: scanner.useDelimiter("\n") this reads the file until it hits the delimiter and starts the next loop from there.
You need to read the file line-by-line and search for your string in every line. The code should look something like:
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputString)) {
// a match!
System.out.println("Found " +inputString+ " in file ");
break;
}
}
Now to decide between Scanner or a BufferedReader to read the file, check this link. Also check this link for fast way of searching a string in file. Also keep in mind to close scanner once you are done.

Replacing a line in a new textfile

I have a textfile with several lines.
Line 1
Line 2
Line 3
Line 4
...
I am trying for example to replace line 3 with a new sentence.
I tred using the code below, but instead of replacing it, it just adds the new sentence next to it and the rest of the text as well. I need it to be removed and place the new sentence in the same spot, and then continue the writing of the rest of the lines. What should I fix?
try {
PrintWriter out = new PrintWriter(new FileWriter(filenew, true));
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains(line 2)) {
line = line.replaceAll("", "new sentence");
}
out.write(line);
out.write("\n");
}
out.flush();
out.close();
scanner.close();
}
catch (IOException e) {
e.printStackTrace();
}
Thanks in advance!
The loop you are looking for is something like
String targetText = "... the text to search";
String replacement = "The new text";
PrintWriter out = mkPrintWriter(/*...*/);
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals(targetText)) {
out.println(replacement);
} else {
out.println(line);
}
}
Note that the out file is a temporary resource. After processing, you can unlink the old file and rename the temp file.
Change
line = line.replaceAll("", "new sentence");
to
line = line.replaceAll(line 2, "new sentence");

Categories