How can I find and replace a word in several text files, using Java?
Here's how I do it for a single String...
public class ReplaceAll {
public static void main(String[] args) {
String str = "We want replace replace word from this string";
str = str.replaceAll("replace", "Done");
System.out.println(str);
}
}
Using FileUtils from Commons IO:
String[] files = { "file1.txt", "file2.txt", "file3.txt" };
for (String file : files) {
File f = new File(file);
String content = FileUtils.readFileToString(new File("filename.txt"));
FileUtils.writeStringToFile(f, content.replaceAll("hello", "world"));
}
You can read in the file using a FileReader wrapped by a BufferedReader, pulling it in line by line, perform the same replace on the string that you show in your question, and write it back out to a new file.
This is the working code: Hope it helps!
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TestIO {
static StringBuilder sbword = new StringBuilder();
static String dirname = null;
static File[] filenames = null;
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws FileNotFoundException, IOException{
boolean fileread = ReadFiles();
sbword = null;
System.exit(0);
}
private static boolean ReadFiles() throws FileNotFoundException, IOException{
System.out.println("Enter the location of folder:");
File file = new File(sc.nextLine());
filenames = file.listFiles();
String line = null;
for(File file1 : filenames ){
System.out.println("File name" + file1.toString());
sbword.setLength(0);
BufferedReader br = new BufferedReader(new FileReader(file1));
line = br.readLine();
while(line != null){
System.out.println(line);
sbword.append(line).append("\r\n");
line = br.readLine();
}
ReplaceLines();
WriteToFile(file1.toString());
}
return true;
}
private static void ReplaceLines(){
System.out.println("sbword contains :" + sbword.toString());
System.out.println("Enter the word to replace from each of the files:");
String from = sc.nextLine();
System.out.println("Enter the new word");
String To = sc.nextLine();
//StringBuilder sbword = new StringBuilder(stbuff);
ReplaceAll(sbword,from,To);
}
private static void ReplaceAll(StringBuilder builder, String from, String to){
int index = builder.indexOf(from);
while(index != -1){
builder.replace(index, index + from.length(), to);
index += to.length();
index = builder.indexOf(from,index);
}
}
private static void WriteToFile(String filename) throws IOException{
try{
File file1 = new File(filename);
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(file1));
bufwriter.write(sbword.toString());
bufwriter.close();
}catch(Exception e){
System.out.println("Error occured while attempting to write to file: " + e.getMessage());
}
}
}
Related
I try to combine information spread across different files, generating a new ArrayList with information somehow based on the original files, and output a new txt which contains the first word of each element of that ArrayList. The problem is my code doesn't end for some reason, and I don't know why.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.IOException;
public class FileReadVaryingAmount {
public static void main(String[] args) throws IOException {
ArrayList<FileInputStream> files = getStreams("letters.txt");
writeFirstWords(files, "myoutput.txt");
}
public static ArrayList<FileInputStream> getStreams(String filenames) {
FileInputStream fis;
Scanner sc;
ArrayList<FileInputStream> inFS = new ArrayList<>();
try {
fis = new FileInputStream(filenames);
sc = new Scanner(fis);
}
catch (Exception e) {
System.out.println("File open error");
return inFS;
}
Scanner scnr = new Scanner(System.in);
try {
while(scnr.hasNextLine()){
String name = scnr.next();
try {
FileInputStream temp = new FileInputStream(name);
Scanner scanner = new Scanner(temp);
while (scanner.hasNext()){
inFS.add(new FileInputStream(scanner.next()));
}
}
catch (Exception e) {
System.out.println("Error.");
}
}
}
catch(Exception e){
System.out.println("Error.");
}
return inFS;
}
public static void writeFirstWords(ArrayList<FileInputStream> list, String outfileName) {
FileOutputStream fileByteStream = null;
PrintWriter outFS = null;
try {
fileByteStream = new FileOutputStream(outfileName);
outFS = new PrintWriter(fileByteStream);
}
catch (Exception e) {
System.out.println("File open error");
}
for (int i = 0; i < list.size(); i++){
outFS.println(list.get(i));
}
outFS.flush();
try {
fileByteStream.close();
outFS.close();
}
catch (Exception e) {
System.out.println("File close error");
}
}
}
and here is the content of the files:
letters.txt
myfile.txt
myfile2.txt
myfile3.txt
myfile.txt
101 102
myfile2.txt
5 101 102 103 104 105
myfile3.txt
1 2 3 4 5
I revised your code and now it works perfectly.
public static void main(String[] args) throws IOException
{
final ArrayList<String> firstWords = getFirstWords("letters.txt");
for (String word : firstWords)
{
System.out.println(word);
}
}
public static ArrayList<String> getFirstWords(String path) throws IOException
{
final ArrayList<String> firstWords = new ArrayList<>();
final BufferedReader input = new BufferedReader(new FileReader(path));
// loop through all lines of the file
String line;
while ((line = input.readLine()) != null)
{
// the line corresponds to another file path
// first line = myfile.txt
// second line = myfile2.txt
// third line = myfile3.txt
firstWords.add(getFirstWordInFile(line));
}
input.close();
return firstWords;
}
public static String getFirstWordInFile(String path) throws IOException
{
final BufferedReader input = new BufferedReader(new FileReader(path));
// read the first line of the file
final String firstLine = input.readLine();
// split this line into separate words
final String[] words = firstLine.split(" ");
final String firstWord = words[0];
input.close();
return firstWord;
}
The output is:
101
5
1
import java.io.*;
import java.util.*;
public class stringstore
{
public static void main(String[] args)
{
File file = new File("C:\\a.txt");
try
{
String strIP="";
Scanner sc = new Scanner(file);
while(sc.hasNext())
{
String line = sc.nextLine();
String str[] = line.split(", ");
strIP = str[0];
}
System.out.println(strIP);
}
catch(IOException e)
{
// work with the errors here
}
}
}
How do I read a nextline from a textfile and display it.
There is only slight mistake in your code.
Try this.
import java.io.*;
import java.util.*;
public class stringstore
{
public static void main(String[] args)
{
File file = new File("C:\\a.txt");
try
{
String strIP="";
Scanner sc = new Scanner(file);
while(sc.hasNext())
{
String line = sc.nextLine();
String str[] = line.split(", ");
strIP = str[0];
System.out.println(strIP);
}
}
catch(IOException e)
{
// work with the errors here
}
}
}
place the print statement inside the loop
You can read file line by line:
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("filename")));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
csv file (test.csv)
Name|Gender
Ali|M
Abu|M
Ahmad|M
Siti|F
Raju|M
properties file (config.properties)
IncomingFileName = test.csv
OuputFileNameExtension = txt
test1.java
public class test1 {
public static Properties prop1 = new Properties();
public static String nameList;
public test1() throws FileNotFoundException, IOException{
InputStream input1 = new FileInputStream("config.properties");
configProp.load(input1);
}
public static void main(String[] args) throws IOException {
test1 t1 = new test1();
t1.readFileLength(configProp.getProperty("IncomingFileName"));
}
public void readFileLength(String filename){
File file = new File(filename);
try(Scanner scanner = new Scanner(file)){
int j = 1;
while (scanner.hasNextLine()) {
String line = scanner.nextLine() + " ";
if (j != 1) {
String[] records = line.split("\\|");
String name = records[0];
String gender = records[1];
nameList = name;
}
j++;
}
if(j != 0){
writeFile("file."+configProp.getProperty
("OutputFileNameExtension"), nameList);
}
scanner.close();
}catch(IOException x){
}
public void writeFile(String fileName, String nameList) throws IOException{
File file = new File(fileName);
FileWriter fileWriter = new FileWriter(file);
System.out.println(nameList); //show one name only
fileWriter.flush();
fileWriter.close();
}
From the above code, I want to write all the name into the csv file.
However, I just can show 1 name only. (i.e Ali). How do I show all the
name in csv file?
Create a linked list of the names: replace String nameList; with LinkedList<String> names = new LinkedList<>();
add each name to the list : replace nameList = name; with names.add(records[0]);
then add the names to the new file:
public void writeFile(String fileName, List<String> names) throws IOException{
File file = new File(fileName);
FileWriter fileWriter = new FileWriter(file);
for(String name: names){
filewriter.write(name);//writes the current name to the file. you may need to add a /n or a "," to the name to get approprite line seperations and comas
}
fileWriter.flush();
fileWriter.close();
}
How about change:
namelist = name
to
namelist = namelist + " " + name
and only calls the writeFile method one time.
Or you could declare namelist as a StringBuilder, and use the append() method to do the same thing.
I want to interchange the last 2 words in a java file.
The file is called text_d.txt and it contains:
Student learns programming java.
and this is the code(below).The output is the same and I don't understand why it does not change.
import java.nio.*;
import java.io.*;
import java.lang.*;
public class Test3 {
public static void main(String[] args) throws Exception {
String s2="text_t.txt";
File _newf = new File("text_d.txt");
changeOrder(_newf);
}
public static void changeOrder(File f) throws Exception {
FileInputStream _inp=new FileInputStream(f.getAbsolutePath());
BufferedReader _rd=new BufferedReader(new InputStreamReader(_inp));
String _p=_rd.readLine();
while (_p != null) {
String [] _b = _p.split(" ");
for(int i = 0; i <= _b.length; i++) {
if(i == 2) {
String aux=_b[i];
_b[i]=_b[i+1];
_b[i+1]=aux;
break;
}
}
_p=_rd.readLine();
}
}
}
For reading, interchanging and writing the file, I suggest you to do something like this:
public class Test3 {
public static void main(String[] args) throws Exception {
String s2="text_t.txt";
File _newf = new File("text_d.txt");
changeOrder(_newf);
}
public static void changeOrder(File f) throws Exception {
FileInputStream _inp = new FileInputStream(f.getAbsolutePath());
BufferedReader _rd = new BufferedReader(new InputStreamReader(_inp));
ArrayList<String[]> newFileContent = new ArrayList<String[]>();
String _p=_rd.readLine();
while (_p != null) {
String [] _b = _p.split(" ");
String temp = _b[_b.length - 2];
_b[_b.length - 2] = _b[_b.length - 1];
_b[_b.length - 1] = temp;
newFileContent.add(_b);
_p=_rd.readLine();
}
PrintWriter writer = new PrintWriter(f.getAbsolutePath(), "UTF-8");
for (String[] line : newFileContent) {
for (String word : line) {
writer.print(word);
}
writer.println();
}
writer.close();
}
There is two minor changes:
First I changed the for loop you used in your code, with 3 lines of code.
Second I used to add all of lines which changed in the while loop in an ArrayList of String arrays which could hold changes in order to save on the file in the future.
And after all, I used an instance of PrintWriter class which could write a file on the hard disk. and in a foreach loop, I wrote contents of new file on the input file.
You could try something like this:
public static void changeOrder(File f) throws Exception {
FileInputStream _inp = new FileInputStream(f.getAbsolutePath());
BufferedReader _rd = new BufferedReader(new InputStreamReader(_inp));
String _p = _rd.readLine();
while (_p != null) {
String [] _b=_p.split(" ");
String temp = _b[_b.length - 1];
_b[_b.length - 1] = _b[_b.length - 2];
_b[_b.length - 2] = temp;
_p = _rd.readLine();
}
}
But if you want the file to be updated you need to write the results to the file...You should use something to write to the file like a PrintWriter.
This should do the trick You want:
public static String changeOrder(File fileName) throws IOException {
Scanner file = new Scanner(fileName);
String line = file.nextLine();
line = line.replace('.', ' ');
String[] items = line.split(" ");
StringBuilder sb = new StringBuilder();
sb.append(items[0] + " ");
sb.append(items[1] + " ");
sb.append(items[3] + " ");
sb.append(items[2] + ".");
return sb.toString();
}
Expected result: Student learns java programming.
This question already has an answer here:
Reading a File From the Computer
(1 answer)
Closed 8 years ago.
I'm trying to read a file from the computer that is in the same folder as the source code and when I run the code is saying: File does not exist
Can you help me ?
import java.io.*;
import java.util.*;
public class Lotto1 {
static String[][] arr;
static String name, number;
public static void main(String[] args) throws IOException {
File f = new File("D:\\Filipe\\Project Final\\src\\database_lotto.txt.txt");
Scanner s;
try {
s = new Scanner(f);
BufferedReader reader = new BufferedReader(new FileReader(f));
int lines = 0;
while(reader.readLine() != null) {
lines++;
}
reader.close();
arr = new String[lines][3];
int count = 0;
//while theres still another line
while(s.hasNextLine()) {
arr[count][0] = s.next() + "" + s.next();
arr[count][1] = s.next();
arr[count][2] = s.next();
count++;
}
} catch(FileNotFoundException ex) {
System.out.println("File does not exist");
}
I've inferred what you're trying to do and recoded it, but this implementation will read the file if it is where you say it is.
public static void main(String[] args) {
final String filename = "database_lotto.txt";
final File lottoFile = new File(filename);
try (final Scanner scanner = new Scanner(lottoFile)) {
final List<String[]> storage = new ArrayList<String[]>();
while (scanner.hasNextLine()) {
storage.add(scanner.nextLine().split(" "));
}
}catch (FileNotFoundException ex) {
System.out.println("File not found :(");
}
}
Are you on Unix/Linux machine?
It is better to use File.separator instead of \, because File.separator uses the system char for a directory (\ on Win, / on Linux etc.)
Use File.exists() to check if file is there, before using it.