How to read a file and perform a find-and-replace? - java

How would I go about going through this text file of the complete book of Huckleberry Finn and replace every occurrence of the word "the" with "a"?
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Filey {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File huck = new File("HuckFinn.txt");
}
}

Figured out this simpler way in class.
import java.io.*;
import java.util.*;
public class Filey {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner s = null;
String meAlong="";
PrintWriter writer = null;
try {
s=new Scanner(new BufferedReader(new FileReader("HuckFinn.txt")));
writer = new PrintWriter("output.txt");
while (s.hasNext())
{
meAlong=s.nextLine();
meAlong=meAlong.replace("the" , "a");
meAlong=meAlong.replace("The", "A");
writer.println(meAlong);
}
}
finally
{
if (s !=null)
{
s.close();
writer.close();
}
}
}
}

Related

How can I change just some part of a name in a file in Java?

I have a file called "ParkPhotos.txt" and inside I have 12 names of some parks, for example "AmericanSamoa1989_photo.jpg". I want to replace the "_photo.jpg" to "_info.txt", but I am struggling. In the code I was able to read the file, but I am not sure how to replace it.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileNameChange {
public static void main(String[] args) throws IOException
{
readFileValues();
}
public static void readFileValues() throws IOException
{
try {
File aFile = new File("ParkPhotos.txt");
Scanner inFile = new Scanner(aFile);
while (inFile.hasNextLine())
{
String parkNames = inFile.nextLine();
System.out.println(parkNames);
}
inFile.close();
} catch (FileNotFoundException e)
{
System.out.println("An error has occurred");
e.printStackTrace();
}
}
}
You can convert to a new content and write it to the current file. For example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
public class FileNameChange {
public static void main(String[] args) throws URISyntaxException {
String newContent = readFileValues();
writeFileValues(newContent);
}
public static String readFileValues() {
StringBuilder newContent = new StringBuilder();
try {
URL url = FileNameChange.class.getClassLoader().getResource("ParkPhotos.txt");
File aFile = new File(url.toURI());
Scanner inFile = new Scanner(aFile);
while (inFile.hasNextLine()) {
String parkName = inFile.nextLine();
if (parkName == null || parkName.isEmpty()) {
continue;
}
newContent.append(parkName.replace("_photo.jpg", "_info.txt"))
.append(System.lineSeparator());
}
inFile.close();
} catch (FileNotFoundException | URISyntaxException e) {
e.printStackTrace();
}
return newContent.toString();
}
public static void writeFileValues(String content) throws URISyntaxException {
URL url = FileNameChange.class.getClassLoader().getResource("ParkPhotos.txt");
File aFile = new File(url.toURI());
try (FileWriter writer = new FileWriter(aFile)) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: the file will be written at build folder. For example: example_1/build/resources/main

How to read .txt file until EOF in java and store into array properly

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MailMessage {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
int i = 0;
String condition = "EOF";
String[] mail = new String[500];
File file = new File("C:\\Users\\sailo\\eclipse-workspace\\mail.txt");
Scanner mailInput = new Scanner(file);
while (mailInput.hasNextLine() && i < 500 && condition != "EOF") {
mail[i] = mailInput.nextLine();
i++;
System.out.print(mail[1] + "\n");
}
}
}
This is what the txt file looks like

bufferedwriter refuses to write to text file(Java)

Whenever I call my method in my code, despite opening and closing my BufferedWriter correctly(I think) it still refuses to print to the text file that it is meant to print to
Here is my code :
public Student(String nameInput, String gradeInput) throws IOException
{
BufferedWriter o = new BufferedWriter(new FileWriter("Students.txt"));
name = nameInput;
grade = gradeInput;
o.write(gradeInput);
o.newLine();
o.write(nameInput);
o.close();
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void Student(String nameInput, String gradeInput) throws IOException
{
BufferedWriter o = new BufferedWriter(new FileWriter("Students.txt"));
String name = nameInput;
String grade = gradeInput;
o.write(gradeInput);
o.newLine();
o.write(nameInput);
o.close();
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Student("ABC","A");
}
}
Try using o.flush() before closing the BufferedWriter i.e.,o.close()

Save the data of a text file in a arraylist

I have a problem with my arraylist; indeed I need to fill my "list_Line" list with the data from my text file (example.txt) but after adding them to my list I can display my list but it seems empty... So did I fill in my list incorrectly or did I go about displaying its content incorrectly (I tried two different methods though) Please what do I have to do to be able to see the data in my text on the console?
Thank you.
Here is my code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Search {
private String path_Fichier;
private static ArrayList<Search> list_Line = new ArrayList<>();
BufferedReader BR = null;
public Search(String pathfichier) {
// TODO Auto-generated constructor stub
this.path_Fichier=pathfichier;
}
void charge(ArrayList list_Line) {
FileReader fichier;
try {
fichier = new FileReader(this.path_Fichier);
BufferedReader BR = new BufferedReader(fichier);
String line;
while((line=BR.readLine())!=null) {
list_Line.add(line);
}
BR.close();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("File not found");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Error");
}
}
void display() {
System.out.println("before");
System.out.println(list_Line);
for (Search m: list_Line) {
System.out.println(m);
System.out.println("between");
}
for (int i=0; i<list_Line.size(); i++) {
System.out.println(list_Line.get(i));
System.out.println("between");
}
System.out.println("after");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Search s = new Search("exemple.txt");
s.display();
}
}
You haven't even called charged() method. Call it and reply.

JAVA Scanner object inside my constructor, cannot call it in my method

I am required to pass a file object to my constructor, and I am required to make a constructor in my method.
I am very confused as to why my code does not compile. It gives me several errors, and i am still struggling with the first one: sc cannot be resolved.
This is my class:
public class Reverser {
public Reverser(File file) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(file);
}
public void reverseLines(File outpr) {
PrintWriter pw = new PrintWriter(outpr);
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
new ArrayList < String > (Arrays.asList(words));
Collections.reverse(wordsarraylist);
if (wordsarraylist != null) {
String listString = wordsarraylist.toString;
listString = listString.subString(1, listString.length() - 1);
}
}
pw.write(listString);
}
}
and this is my main:
import java.util.*;
import java.io.*;
public class ReverserMain {
public static void main(String[] args) throws FileNotFoundException, IOException {
Reverser r = new Reverser(new File("test.txt"));
}
}
Are you adding more functions to this class? You can keep it simple with an approach like this:
public static void reverseLines(File inputFile, File outPutFile) {
try (Scanner sc = new Scanner(inputFile); PrintWriter pw = new PrintWriter(outPutFile)) {
while (sc.hasNextLine()) {
// your logic goes in here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You can use try-catch block with resources, will auto close the streams.
And when you are writing to the output file,if the file is already existing, do you want to append data or erase the contents of the file and write to a completely new file??
if you must use constructors:
public class Reverser {
File inputFile;
File outputFile;
public Reverser(File inputFile, File outputFile) {
this.inputFile = inputFile;
this.outputFile = outputFile;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void reverseLines() {
try (Scanner sc = new Scanner(inputFile); PrintWriter pw = new PrintWriter(outputFile)) {
while (sc.hasNextLine()) {
// your logic goes in here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Declare sc outside of the constructor :
Scanner sc = null ;
public Reverser(File file)throws FileNotFoundException, IOException{
sc = new Scanner (file);
}

Categories