java homework with word replacement - java

Hello can someone help me? The point of the homework is to read a file then create another file where it replaces all of the words "is" with "was", i have all this done but I am also not sopposed to replace words that have"is" in them, for example: "this, isthmus".
import java.io.*;
import java.util.*;
public class WordChange {
public static void main(String[]args) throws Exception {
FileReader fr = null;
FileWriter fw = null;
try
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the name of the text file: ");
String fileName=keyboard.nextLine();
File file = new File(fileName);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
String replacedtext=oldtext.replaceAll("is ","was ");
FileWriter writer = new FileWriter("output.txt");
writer.write(replacedtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}

just a guess here but instead of
String replacedtext=oldtext.replaceAll("is ","was ");
would this work
String replacedtext=oldtext.replaceAll(" is "," was ");
Im just guessing let me know if it works

Related

How can I delete lines of data in textfile using java? eg. my textfile is data.txt

From read the line needed to be deleted by the user to delete it
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Delete {
public static void main(String[] args) throws IOException {
File input = new File("data.txt");
FileReader fr = null;
Scanner ob = new Scanner(System.in);
// declare variable
String DeleteWord, str, newDeleteWord;
System.out.print("Enter word you want to delete: ");
DeleteWord = ob.nextLine();
newDeleteWord = (capitalize(DeleteWord));
try {
fr = new FileReader(input);
BufferedReader br = new BufferedReader(fr);
while ((str = br.readLine()) != null) {
if (str.contains(newDeleteWord)) {
System.out.println(str);
}
Scanner read = new Scanner(System.in);
int selection;
System.out.println("Confirm to delete his/her data?\n 1 for yes\n 2 for no");
selection = read.nextInt();
if (selection == 1)
if (str.contains(newDeleteWord)) {
str = "";
}
}
} finally {
fr.close();
}
}
public static String capitalize(String str1) {
if (str1 == null || str1.isEmpty()) {
return str1;
}
return str1.substring(0, 1).toUpperCase() + str1.substring(1);
}
}
How can I delete lines of data in textfile using java? eg. my textfile is data.txt
This is a possible solution:
File inputFile = new File("myFile.txt"); // File which we will read
File tempFile = new File("myTempFile.txt"); // The temporary file where we will write
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = yourString; // here is your line to remove
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim(); // we trim it and remove unecessary spaces
if(trimmedLine.equals(lineToRemove)) continue; // If it is equal to our line to remove then do not write it to our file!
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete(); // we delete the file that we have so that we have no conflicts
boolean successful = tempFile.renameTo(inputFile);
OR
Reading all the lines in a list and filtering this list.
The quickest way is through Apache Commons-IO ( or you can implement it yourself)
Apache Commons:
List<String> lines = FileUtils.readLines(file);
List<String> updatedLines = lines.stream().filter(s -> !s.contains(searchString)).collect(Collectors.toList());
FileUtils.writeLines(file, updatedLines, false);

Remove specific line from txt file

Hello i need to delete a specific line from text file after ID search p.g. ID=2
students.txt
1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman
And after search and delete to get:
students.txt
1,Giannis,Oreos,Man
3,Maria,Oaka,Woman
But is not working properly
Code so far:
#FXML
TextField ID2;
#FXML
public void UseDelete() throws IOException {
File inputFile = new File("src/inware/students.txt");
File tempFile = new File("src/inware/studentsTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = ID2.getText();
String currentLine;
while ((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if (trimmedLine.equals(lineToRemove)) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
}
If you want to remove a line by a line number I guess you can do a change to your code like this. You can give the int value of Id to the lineToRemove variable instead of my hard coded value
import java.io.*;
public class A {
public static void main(String[] args) throws IOException {
new A().useDelete();
}
public void useDelete() throws IOException {
File inputFile = new File("src/inware/students.txt");
File tempFile = new File("src/inware/studentsTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
int lineToRemove = 2;
String currentLine;
int count = 0;
while ((currentLine = reader.readLine()) != null) {
count++;
if (count == lineToRemove) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
}

File Writer and File Reader error

I have this code to read from a text file and then modify it. Then write the modified content to another text file.
I am getting a null pointer exception at out.write(read); And also, not all lines are being written, can some one help me please. Thank you
import java.util.*;
import java.io.*;
public class File
{
BufferedReader in;
BufferedWriter out;
String read;
public File()
{
try {
in = new BufferedReader(new FileReader("myFile.txt"));
Scanner scan = new Scanner(in);
out = new BufferedWriter(new FileWriter("output.txt"));
while (scan.hasNext()) {
read = in.readLine();
//Write codes to modify file here
//___codes not written yet______//
out.write(read);
scan.next();
System.out.println("file output: " + read);
}
out.close();
in.close();
} catch (IOException e) {
System.out.println("There was a problem:" + e);
}
}
public static void main(String[] args)
{
File File = new File();
}
}
try
while((read = in.readLine()) != null)
instead of
while (scan.hasNext())
need to change :while((read = in.readLine()) != null).

removing extra white spaces from text files

I have number of text files in the following format:
196903274115371008 #266093898
Prince George takes his first public steps with his mom, Catherine, Duchess of
Cambridge.
I would like to remove all extra while spaces + new line characters except the first new line characters. So I would like to above to be like this:
196903274115371008#266093898
Prince George takes his first public steps with his mom, Catherine, Duchess of Cambridge.
I wrote the following code :
package remove_white_space222;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Remove_white_space222 {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
line=line.replaceAll("\\s+", " ");
fw.write(line);
}
fr.close();
fw.close();
}
}
Thanks in advance for your help,,,,
File file = new File("input_file.txt");
try(BufferedReader br = new BufferedReader(new FileReader(file));
FileWriter fw = new FileWriter("empty_file.txt")) {
String st;
while((st = br.readLine()) != null){
fw.write(st.replaceAll("\\s+", " ").trim().concat("\n"));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here's one approach:
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;
int lineNum = 0;
while((line = br.readLine()) != null)
{
//check if we are working with the first two lines
//(which should remain untouched)
if (lineNum > 1) {
//make sure we ignore any empty lines
if (line.trim().length() > 0) {
//add a space to the end of each line to make
//padding before we append the next line.
line=line.trim().replaceAll("\\s+", " ") + " ";
}
} else {
//remove all whitespace.
line = line.trim().replaceAll("\\s", "");
line = line + "\n";
}
fw.write(line);
lineNum++;
}
fr.close();
fw.close();
}
Output:
196903274115371008#266093898
Prince George takes his first public steps with his mom, Catherine, Duchess of Cambridge. %
You can use status via an enum to add newlines after first line and all empty lines following it.
package remove_white_space222;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter
import java.io.IOException;
public class Remove_white_space222 {
enum Status {
FIRST, EMPTY, NORMAL;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
PrintWriter pw = new PrintWriter(fw);
String line;
while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
line=line.replaceAll("\\s+", " ");
fw.write(line);
if (status != Status.NORMAL) {
if ((status == Status.FIRST) || line.isEmpty()) {
pw.println();
status = Status.EMPTY;
} else {
status = Status.NORMAL;
}
}
}
fr.close();
fw.close();
}
}
You can keep your logic for all the lines but line 1 (the 2nd line), just stick "\n\n" in that case, so you have an empty line.
Also, I'd advise to open your resources in the try this way you don't have to worry about closing them
try(FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt") ) {
String line;
int lineNumber = 0;
while((line = br.readLine()) != null) {
if(lineNumber == 1) {
line = "\n\n";
} else {
line = line.trim().replaceAll("\\s+", " ");
}
fw.write(line);
lineNumber++;
}
}
Outputs:
196903274115371008 #266093898
Prince George takes his first public steps with his mom, Catherine, Duchess ofCambridge.

How to print lines from a file that contain a specific word using java?

How to print lines from a file that contain a specific word using java ?
Want to create a simple utility that allows to find a word in a file and prints the complete line in which given word is present.
I have done this much to count the occurence but don't knoe hoe to print the line containing it...
import java.io.*;
public class SearchThe {
public static void main(String args[])
{
try
{
String stringSearch = "System";
BufferedReader bf = new BufferedReader(new FileReader("d:/sh/test.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("Word is at position " + indexfound + " on line " + linecount);
}
}
bf.close();
}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
Suppose you are reading from a file named file1.txt Then you can use the following code to print all the lines which contains a specific word. And lets say you are searching for the word "foo".
import java.util.*;
import java.io.*;
public class Classname
{
public static void main(String args[])
{
File file =new File("file1.txt");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("foo"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Hope this code helps.
public static void grep(Reader inReader, String searchFor) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(inReader);
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchFor)) {
System.out.println(line);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
Usage:
grep(new FileReader("file.txt"), "GrepMe");
Have a look at BufferedReader or Scanner for reading the file.
To check if a String contains a word use contains from the String-class.
If you show some effort I'm willing to help you out more.
you'll need to do something like this
public void readfile(){
try {
BufferedReader br;
String line;
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("file path"), "UTF-8");
br = new BufferedReader(inputStreamReader);
while ((line = br.readLine()) != null) {
if (line.contains("the thing I'm looking for")) {
//do something
}
//or do this
if(line.matches("some regular expression")){
//do something
}
}
// Done with the file
br.close();
br = null;
}
catch (Exception ex) {
ex.printStackTrace();
}
}

Categories

Resources