How do I replace a line of text found within a text file?
I have a string such as:
Do the dishes0
And I want to update it with:
Do the dishes1
(and vise versa)
How do I accomplish this?
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JCheckBox checkbox = (JCheckBox) e.getSource();
if (checkbox.isSelected()) {
System.out.println("Selected");
String s = checkbox.getText();
replaceSelected(s, "1");
} else {
System.out.println("Deselected");
String s = checkbox.getText();
replaceSelected(s, "0");
}
}
};
public static void replaceSelected(String replaceWith, String type) {
}
By the way, I want to replace ONLY the line that was read. NOT the entire file.
At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the StringBuffer "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
String inputStr = inputBuffer.toString();
System.out.println(inputStr); // display the original file for debugging
// logic to replace lines in the string (could use regex here to be generic)
if (type.equals("0")) {
inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0");
} else if (type.equals("1")) {
inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
}
// display the new file for debugging
System.out.println("----------------------------------\n" + inputStr);
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputStr.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Then call it:
public static void main(String[] args) {
replaceSelected("Do the dishes", "1");
}
Original Text File Content:
Do the dishes0
Feed the dog0
Cleaned my room1
Output:
Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1
New text file content:
Do the dishes1
Feed the dog0
Cleaned my room1
And as a note, if the text file was:
Do the dishes1
Feed the dog0
Cleaned my room1
and you used the method replaceSelected("Do the dishes", "1");,
it would just not change the file.
Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).
// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
try {
// input the (modified) file content to the StringBuffer "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
line = ... // replace the line here
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputBuffer.toString().getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Since Java 7 this is very easy and intuitive to do.
List<String> fileContent = new ArrayList<>(Files.readAllLines(FILE_PATH, StandardCharsets.UTF_8));
for (int i = 0; i < fileContent.size(); i++) {
if (fileContent.get(i).equals("old line")) {
fileContent.set(i, "new line");
break;
}
}
Files.write(FILE_PATH, fileContent, StandardCharsets.UTF_8);
Basically you read the whole file to a List, edit the list and finally write the list back to file.
FILE_PATH represents the Path of the file.
If replacement is of different length:
Read file until you find the string you want to replace.
Read into memory the part after text you want to replace, all of it.
Truncate the file at start of the part you want to replace.
Write replacement.
Write rest of the file from step 2.
If replacement is of same length:
Read file until you find the string you want to replace.
Set file position to start of the part you want to replace.
Write replacement, overwriting part of file.
This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work.
Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. If encoding is UTF8, and your text is not Latin1 (or plain 7-bit ASCII), you have to check length of encoded byte array, not length of Java string.
I was going to answer this question. Then I saw it get marked as a duplicate of this question, after I'd written the code, so I am going to post my solution here.
Keeping in mind that you have to re-write the text file. First I read the entire file, and store it in a string. Then I store each line as a index of a string array, ex line one = array index 0. I then edit the index corresponding to the line that you wish to edit. Once this is done I concatenate all the strings in the array into a single string. Then I write the new string into the file, which writes over the old content. Don't worry about losing your old content as it has been written again with the edit. below is the code I used.
public class App {
public static void main(String[] args) {
String file = "file.txt";
String newLineContent = "Hello my name is bob";
int lineToBeEdited = 3;
ChangeLineInFile changeFile = new ChangeLineInFile();
changeFile.changeALineInATextFile(file, newLineContent, lineToBeEdited);
}
}
And the class.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class ChangeLineInFile {
public void changeALineInATextFile(String fileName, String newLine, int lineNumber) {
String content = new String();
String editedContent = new String();
content = readFile(fileName);
editedContent = editLineInContent(content, newLine, lineNumber);
writeToFile(fileName, editedContent);
}
private static int numberOfLinesInFile(String content) {
int numberOfLines = 0;
int index = 0;
int lastIndex = 0;
lastIndex = content.length() - 1;
while (true) {
if (content.charAt(index) == '\n') {
numberOfLines++;
}
if (index == lastIndex) {
numberOfLines = numberOfLines + 1;
break;
}
index++;
}
return numberOfLines;
}
private static String[] turnFileIntoArrayOfStrings(String content, int lines) {
String[] array = new String[lines];
int index = 0;
int tempInt = 0;
int startIndext = 0;
int lastIndex = content.length() - 1;
while (true) {
if (content.charAt(index) == '\n') {
tempInt++;
String temp2 = new String();
for (int i = 0; i < index - startIndext; i++) {
temp2 += content.charAt(startIndext + i);
}
startIndext = index;
array[tempInt - 1] = temp2;
}
if (index == lastIndex) {
tempInt++;
String temp2 = new String();
for (int i = 0; i < index - startIndext + 1; i++) {
temp2 += content.charAt(startIndext + i);
}
array[tempInt - 1] = temp2;
break;
}
index++;
}
return array;
}
private static String editLineInContent(String content, String newLine, int line) {
int lineNumber = 0;
lineNumber = numberOfLinesInFile(content);
String[] lines = new String[lineNumber];
lines = turnFileIntoArrayOfStrings(content, lineNumber);
if (line != 1) {
lines[line - 1] = "\n" + newLine;
} else {
lines[line - 1] = newLine;
}
content = new String();
for (int i = 0; i < lineNumber; i++) {
content += lines[i];
}
return content;
}
private static void writeToFile(String file, String content) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) {
writer.write(content);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String readFile(String filename) {
String content = null;
File file = new File(filename);
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return content;
}
}
Sharing the experience with Java Util Stream
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public static void replaceLine(String filePath, String originalLineText, String newLineText) {
Path path = Paths.get(filePath);
// Get all the lines
try (Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8)) {
// Do the line replace
List<String> list = stream.map(line -> line.equals(originalLineText) ? newLineText : line)
.collect(Collectors.toList());
// Write the content back
Files.write(path, list, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.error("IOException for : " + path, e);
e.printStackTrace();
}
}
Usage
replaceLine("test.txt", "Do the dishes0", "Do the dishes1");
//Read the file data
BufferedReader file = new BufferedReader(new FileReader(filepath));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
String inputStr = inputBuffer.toString();
// logic to replace lines in the string (could use regex here to be generic)
inputStr = inputStr.replace(str, " ");
//'str' is the string need to update in this case it is updating with nothing
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream(filer);
fileOut.write(inputStr.getBytes());
fileOut.close();
Well you would need to get a file with JFileChooser and then read through the lines of the file using a scanner and the hasNext() function
http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html
once you do that you can save the line into a variable and manipulate the contents.
just how to replace strings :) as i do
first arg will be filename second target string third one the string to be replaced instead of targe
public class ReplaceString{
public static void main(String[] args)throws Exception {
if(args.length<3)System.exit(0);
String targetStr = args[1];
String altStr = args[2];
java.io.File file = new java.io.File(args[0]);
java.util.Scanner scanner = new java.util.Scanner(file);
StringBuilder buffer = new StringBuilder();
while(scanner.hasNext()){
buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
if(scanner.hasNext())buffer.append("\n");
}
scanner.close();
java.io.PrintWriter printer = new java.io.PrintWriter(file);
printer.print(buffer);
printer.close();
}
}
I need to manipulate this code so that it will read the # of digits from a file.
I am honestly stumped on this one for some reason. Do i need to tokenize it first?
Thanks!
import java.io.*;
import java.util.*;
public class CountLetters {
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Synopsis: Java CountLetters inputFileName");
System.exit(1);
}
String line = null;
int numCount = 0;
try {
FileReader f = new FileReader(args[0]);
BufferedReader in = new BufferedReader(f);
while ((line = in.readLine()) != null) {
for (int k = 0; k < line.length(); ++k)
if (line.charAt(k) >= 0 && line.charAt(k) <= 9)
++numCount;
}
in.close();
f.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(numCount + " numbers in this file.");
} // main
} // CountNumbers
Use '' to indicate a char constant (you are comparing chars to ints), also I would suggest you use try-with-resources Statement to avoid explicit close calls and please avoid using one line loops without braces (unless you are using lambdas). Like
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Synopsis: Java CountLetters inputFileName");
System.exit(1);
}
String line = null;
int numCount = 0;
try (BufferedReader in = new BufferedReader(new FileReader(args[0]))) {
while ((line = in.readLine()) != null) {
for (int k = 0; k < line.length(); ++k) {
if ((line.charAt(k) >= '0' && line.charAt(k) <= '9')) {
++numCount;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(numCount + " numbers in this file.");
} // main
Also, you could use a regular expression to remove all non-digits (\\D) and add the length of the resulting String (which is all-digits). Like,
while ((line = in.readLine()) != null) {
numCount += line.replaceAll("\\D", "").length();
}
Use if(Charachter.isDigit(char)) replace char with each char, this will count each number, and I believe arabic numbers as well.
What I am trying to do here is read a file and count each character. Each character should add +1 to the "int count" and then print out the value of "int count".
I hope that what I am trying to do is clear.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
int count = 0;
Scanner scan = null;
Scanner cCount = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("greeting")));
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
finally {
if (scan != null) {
scan.close();
}
}
try {
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext("")) {
count++;
}
}
finally {
if (cCount != null) {
scan.close();
}
}
System.out.println(count);
}
}
Add a catch block to check for exception
Remove the parameter from hasNext("")
Move to the next token
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext()) {
count = count + (cCount.next()).length();
}
Using java 8 Stream API, you can do it as follow
package example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountCharacter {
private static int count=0;
public static void main(String[] args) throws IOException {
Path path = Paths.get("greeting");
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
count = lines.collect(Collectors.summingInt(String::length));
}
System.out.println("The number of charachters is "+count);
}
}
Well if your looking for a way to count only all chars and integers without any blank spaces and things like 'tab', 'enter' etc.. then you could first remove those empty spaces using this function:
st.replaceAll("\\s+","")
and then you would just do a string count
String str = "a string";
int length = str.length( );
First of all, why would you use try { } without catch(Exception e)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("greetings.txt"));
String line = null;
String text = "";
while ((line = reader.readLine()) != null) {
text += line;
}
int c = 0; //count of any character except whitespaces
// or you can use what #Alex wrote
// c = text.replaceAll("\\s+", "").length();
for (int i = 0; i < text.length(); i++) {
if (!Character.isWhitespace(text.charAt(i))) {
c++;
}
}
System.out.println("Number of characters: " +c);
} catch (IOException e) {
System.out.println("File Not Found");
} finally {
if (reader != null) { reader.close();
}
}
I'm trying to wraite a Java program that reads input in text file and compares 1s to 0s. The result is equal when the frequency of 1s are equal to the frequency of 0s.
Example:
Input.txt
1100
100
101
10
Output.txt
Equal!
Not Equal!
Not Equal!
Equal
This is the code I'm working with:
package automata;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader freader = new FileReader("Input.txt");
BufferedReader br = new BufferedReader(freader);
try
{
String s="";
while((s = br.readLine()) != null)
{
int count = 0;
for(int i = 0 ; i < s.length() ; i++)
{
if(s.charAt(i) == '0') count++;
else if(s.charAt(i) == '1') count--;
}
if(count == 0) System.out.print("Equal!\n");
else System.out.print("Not Equal! \n");
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
That's how I'd do it.
import java.io.*;
public class TestFile
{
public TestFile()
{
File inputFile = new File("input.txt"),
outputFile = new File("output.txt");
try
{
FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String s;
while((s = br.readLine()) != null)
{
int count = 0;
for(int i = 0 ; i < s.length() ; i++)
{
if(s.charAt(i) == '0') count++;
else if(s.charAt(i) == '1') count--;
}
if(count == 0) bw.append("Equal!\n");
else bw.append("Not Equal! \n");
}
br.close();
bw.close();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
new TestFile();
}
}
If you iterate over every character of each line,
you could count the ones or zeros and compare the result to the half of the length on the complete string.
you could use a counter initialized to zero and count one up for every one and one down for every zero, so you would have it zero on equal number of ones and zeros
Aditionally, if you get a really big amount of data (lots of lines and very long lines) it may make sense to check regulary if a line can be equal before you reach it's end (if you have 1001 ones on a 2000 charater line, you don't need to check any more and saved 999 itertions).
I am trying to get the number of lines of code from a java file. But I am having trouble counting them.
First I tried to skip them with ifs, but my idea does not work. Now I am counting the same lines with comments, my Java file has this header. Any ideas, I am stuck in how to count them.
My if is for getting the number of lines with the comments block. I trying to make a subtract.
/*
example
example
*/
int totalLoc = 0;
int difference = 0;
while((line =buff.readLine()) !=null){
if((line.trim().length() !=0 &&(!line.contains("/*") ||!line.contains("*/")) )){
if(line.startsWith("/*")){
difference++;
}else if(linea.startsWith("*/")){
difference++;
}else{
difference++;
}
}
}
If you want to count lines in any file write below method and pass the fileName as input to below method and it will return counts.
public int count(String filename) throws IOException
{
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try
{
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1)
{
empty = false;
for (int i = 0; i < readChars; ++i)
{
if (c[i] == '\n')
++count;
}
}
return (count == 0 && !empty) ? 1 : count;
}
finally
{
is.close();
}
}
Got the solution try below code it will print all multiline comments as well as total lines of multiline comments found in a file.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LinesOfCode {
public static void main(String[] args) {
try {
String s = readFile("D:\\src\\SampleClass.java");
Pattern p = Pattern.compile("/\\*[\\s\\S]*?\\*/");
Matcher m = p.matcher(s);
int total = 0;
while (m.find()) {
String lines[] = m.group(0).split("\n");
for (String string : lines) {
System.out.println(string);
total++;
}
}
System.out.println("Total line for comments = " + total);
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
fc.size());
/* Instead of using default, pass in a decoder. */
return Charset.defaultCharset().decode(bb).toString();
} finally {
stream.close();
}
}
}
http://ostermiller.org/findcomment.html
check out this link it will help you more.
and by using this expression => (/*([^]|[\r\n]|(*+([^/]|[\r\n])))*+/)|(//.)
you can count both comments single line and multi line !!