Reverse lines in ArrayList Java - java

I'm working on a Java program in which I must read the contents of a file and then print each lines reverse. For example the text:
Public Class Helloprinter
Public static void
would print the following after running my reverse program:
retnirPolleh ssalc cilbup
diov citats cilbup
Here's what I got so far:
public static void main(String[] args) throws FileNotFoundException {
// Prompt for the input and output file names
ArrayList<String> list = new ArrayList<String>();
//String reverse = "";
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
String aString = "";
while(in.hasNextLine())
{
String line = in.nextLine();
list.add(line);
}
in.close();
for(int i = 0; i <list.size(); i++)
{
aString = list.get(i);
aString = new StringBuffer(aString).reverse().toString();
out.printf("%s", " " + aString);
}
out.close();
}
}
EDIT:
With Robert's posting it helped put me in the right direction. The problem is that with that is that it doesn't keep the lines.
Public Class Helloprinter
Public static void
becomes after running my program:
retnirPolleh ssalc cilbup diov citats cilbup
it needs to keep the line layout the same. so it should be:
retnirPolleh ssalc cilbup
diov citats cilbup

Your problem is in the line
out.printf("%s", " " + aString);
This doesn't output a newline. I'm also not sure why you are sticking a space in there.
It should be either:
out.println( aString );
Or
out.printf("%s%n", aString);

In your last loop why don't you just iterate through the list backwards? So:
for(int i = 0; i <list.size(); i++)
Becomes:
for(int i = list.size() - 1; i >=0; i--)

It seems like you already know how to read a file, so then call this method for each line.
Note, this is recursion and it's probably not the most efficient but it's simple and it does what you want.
public String reverseString(final String s) {
if (s.length() == 0)
return s;
// move chahctrachter at current position and then put it at the end of the string.
return reverseString(s.substring(1)) + s.charAt(0);
}

Just use a string builder. You were on the right trail. Probably just needed a little help. There is no "one way" to do anything, but you could try something like this:
Note: Here is my output: retnirPolleh ssalc cilbup diov citats cilbup
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
ArrayList<String> myReverseList = null;
System.out.println("Input file: \n");
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
System.out.println("Output file: \n");
String outputFileName = input.nextLine();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String text = null;
myReverseList = new ArrayList<String>();
StringBuilder sb = null;
try {
while ((text = br.readLine()) != null) {
sb = new StringBuilder();
for (int i = text.length() - 1; i >= 0; i--) {
sb.append(text.charAt(i));
}
myReverseList.add(sb.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFileName), "utf-8"));
for (String s : myReverseList) {
writer.write("" + s + "\n");
}
} catch (IOException ex) {
// report
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
}
}

Related

Indexing through an array to return any specific value in java

So, I have created code which is reading a CSV file line by line, then splitting each line into their individual values then putting this into an array, but i am stuck on trying the index a value from this array I have created, I will attach the CSV file and also my code, and lets say for example how would I access the value at [3,4], which should be Andorra, and [6,6] which should be 17?
CSV FILE:
Date,iso3,Continent,CountryName,lat,lon,CumulativePositive,CumulativeDeceased,CumulativeRecovered,CurrentlyPositive,Hospitalized,IntensiveCare,NUTS
31/1/2021,AFG,AS,Afghanistan,33.930445,67.678945,55023,2400,,52623,,,AF
31/1/2021,ALB,EU,Albania,41.156986,20.181222,78127,1380,47424,29323,324,19,AL
31/1/2021,DZA,AF,Algeria,28.026875,1.65284,107122,2888,,104234,,,DZ
31/1/2021,AND,EU,Andorra,42.542268,1.596865,9937,101,,9836,44,,AD
31/1/2021,AGO,AF,Angola,-11.209451,17.880669,19782,464,,19318,,,AO
31/1/2021,AIA,NA,Anguilla,18.225119,-63.07213,17,0,,17,,,AI
31/1/2021,ATG,NA,Antigua and Barbuda,17.363183,-61.789423,218,7,,211,,,AG
31/1/2021,ARG,SA,Argentina,-38.421295,-63.587403,1915362,47775,,1867587,,,AR
31/1/2021,ARM,AS,Armenia,40.066181,45.111108,167026,3080,,163946,,,AM
31/1/2021,ABW,NA,Aruba,12.517713,-69.965112,6858,58,,6800,,,AW
31/1/2021,AUS,OC,Australia,-26.853388,133.275154,28806,909,,27897,,,AU
31/1/2021,AUT,EU,Austria,47.697542,13.349319,411921,7850,383158,21058,1387,297,AT
31/1/2021,AZE,AS,Azerbaijan,40.147396,47.572098,229935,3119,,226816,,,AZ
31/1/2021,BHS,NA,Bahamas,24.885993,-76.709892,8174,176,,7998,,,BS
31/1/2021,BHR,AS,Bahrain,26.039722,50.559306,102626,372,,102254,,,BH
31/1/2021,BGD,AS,Bangladesh,23.68764,90.351002,535139,8127,,527012,,,BD
31/1/2021,BRB,NA,Barbados,13.18355,-59.534649,1498,12,,1486,,,BB
31/1/2021,BLR,EU,Belarus,53.711111,27.973847,248336,1718,,246618,,,BY
31/1/2021,BEL,EU,Belgium,50.499527,4.475402,711417,21118,,690299,1788,315,BE
31/1/2021,BLZ,NA,Belize,17.192929,-88.5009,11877,301,,11576,,,BZ
31/1/2021,BEN,AF,Benin,9.322048,2.313138,3786,48,,3738,,,BJ
31/1/2021,BMU,NA,Bermuda,32.320236,-64.774022,691,12,,679,,,BM
31/1/2021,BTN,AS,Bhutan,27.515709,90.442455,859,1,,858,,,BT
31/1/2021,BWA,AF,Botswana,-22.344029,24.680158,21293,134,,21159,,,BW
31/1/2021,BRA,SA,Brazil,-14.242915,-53.189267,9118513,222666,,8895847,,,BR
31/1/2021,VGB,NA,British Virgin Islands,18.573601,-64.492065,141,1,,140,,,VG
CODE:
public static String readFile(String file) {
FileInputStream fileStream = null;
InputStreamReader isr;
BufferedReader bufRdr;
int lineNum;
String line = null;
try {
fileStream = new FileInputStream(file);
isr = new InputStreamReader(fileStream);
bufRdr = new BufferedReader(isr);
lineNum = 0;
line = bufRdr.readLine();
while ((line != null) && lineNum < 27) {
lineNum++;
System.out.println(line);
line = bufRdr.readLine();
}
fileStream.close();
}
catch (IOException e) {
if (fileStream != null) {
try {
fileStream.close();
}
catch (IOException ex2) {
}
}
System.out.println("Error: " + e.getMessage());
}
return line;
}
private static void processLine(String line) {
String[] splitLine;
splitLine = line.split(",");
int lineLength = splitLine.length;
for (int i = 0; i < lineLength; i++) {
System.out.print(splitLine[i] + " ");
}
System.out.println("");
}
You need to create a 2D array in readFile. As the file is read, and and each line is split by processLine, insert the array into the 2D array. The method readFile at the end returns the 2D array. Make processLine to return a string array and have it return the result of the split.
I marked where I made changes to your code.
import java.io.*;
public class Main
{
public static void main(String[] args){
String[][] data = readFile("data.txt");
System.out.println(data[3][4]);
System.out.println(data[6][6]);
}
public static String[][] readFile(String file) { //<<< changed
FileInputStream fileStream = null;
InputStreamReader isr;
BufferedReader bufRdr;
int lineNum;
String line = null;
String[][] data = new String[28][]; //<<< added
try {
fileStream = new FileInputStream(file);
isr = new InputStreamReader(fileStream);
bufRdr = new BufferedReader(isr);
lineNum = 0;
line = bufRdr.readLine();
while (lineNum < 27) { // <<< changed
System.out.println(line);
line = bufRdr.readLine();
if (line == null) break; // <<< added
data[lineNum++] = processLine(line); // <<< added
}
fileStream.close();
}
catch (IOException e) {
if (fileStream != null) {
try {
fileStream.close();
}
catch (IOException ex2) {
}
}
System.out.println("Error: " + e.getMessage());
}
return data; //added
}
private static String[] processLine(String line) { //<< changed
String[] splitLine;
splitLine = line.split(",");
int lineLength = splitLine.length;
for (int i = 0; i < lineLength; i++) {
System.out.print(splitLine[i] + " ");
}
System.out.println("");
return splitLine; // <<< added
}
}
You can do it quite simply using the stream API.
import java.io.IOException;
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 CsvTest0 {
public static void main(String[] args) {
Path path = Paths.get("geografy.csv");
try (Stream<String> lines = Files.lines(path)) {
String[][] arr = lines.skip(1L)
.limit(27L)
.map(l -> l.split(","))
.collect(Collectors.toList())
.toArray(new String[][]{});
System.out.println(arr[3][3]);
System.out.println(arr[5][6]);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
However, regarding the code in your question, below is a fixed version followed by notes and explanations.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CsvTest1 {
public static String[][] readFile(String file) throws IOException {
Path path = Paths.get(file);
String[][] arr = new String[27][];
int lineNum;
String line = null;
try (BufferedReader bufRdr = Files.newBufferedReader(path)) {
lineNum = 0;
line = bufRdr.readLine(); // Ignore first line of file since it contains headings only.
line = bufRdr.readLine();
while ((line != null) && lineNum < 27) {
arr[lineNum++] = processLine(line);
line = bufRdr.readLine();
}
}
return arr;
}
private static String[] processLine(String line) {
return line.split(",");
}
public static void main(String[] args) {
try {
String[][] arr = readFile("geografy.csv");
System.out.println(arr[3][3]);
System.out.println(arr[5][6]);
}
catch (IOException x) {
x.printStackTrace();
}
}
}
Note that the below is not in any particular order. I wrote them as they came to me.
No need for FileInputStream and InputStreamReader in order to create BufferedReader. Use Files class instead.
Close files in a finally block and not in a catch block. Hence use try-with-resources.
I believe better to propagate the exception to the calling method, i.e. method main in this case. I also believe that, unless you can safely ignore the exception, it is always beneficial to print the stack trace.
You don't want to process the first line of the file.
You appear to have your array indexes mixed up. According to sample data, Andorra is row 3 and column 3 (not column 4). Also, 17 is at [5][6] and not [6][6].
Two-dimensional arrays in java can be declared with only one dimension indicated. Since you only want first 27 lines of file, you know how many rows will be in the 2D array.

Why my Java program works perfectly in windows but it's a disaster in linux?

I wrote a program that reads a text file, deletes the requested string and rewrites it without the string. This program takes three arguments from the terminal: 1) the input file 2) the string 3) the output file.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class wordfilter {
public static void main(String[] args) {
Scanner scanner = new Scanner("");
Scanner conteggio = new Scanner("");
int numel = 0;
File file = new File(args[0]); // Argomento 0: il file
try {
conteggio = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (conteggio.hasNext()) {
numel++;
conteggio.next();
}
conteggio.close();
String[] lettura = new String[numel];
int i = 0;
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
System.out.println("Contarighe -> " + numel);
for (i = 0; i < lettura.length; i++) {
System.out.println("Elemento " + i + " - > " + lettura[i]);
}
scanner.close();
String escludi = args[1]; // Argomento 1: il filtro
String[] filtrato = rimuovi(escludi, lettura);
if (args.length == 3) stampaSuFile(filtrato, args[2]);
}
public static String[] rimuovi(String esclusione, String[] input) {
String[] nuovoV;
String escludi = esclusione;
int dim = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi))
dim++;
}
nuovoV = new String[dim];
int j = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi)) {
nuovoV[j] = input[i];
j++;
}
;
}
return nuovoV;
}
public static void stampaSuFile(String[] out, String path) {
String closingstring = "";
File destinazione = new File(path);
try {
destinazione.createNewFile();
} catch (IOException e) {
System.out.println("Errore creazione file");
}
try {
FileWriter writer = new FileWriter(destinazione);
for (int i = 0; i < out.length; i++)
writer.write(out[i] + (i == (out.length-1) ? closingstring : " "));
writer.close();
System.out.println("Scrittura eseguita correttamente");
} catch (IOException e) {
System.out.println("Errore scrittura file");
}
}
}
On Windows no problem, it works perfectly.
On Linux instead when i write something like java wordfilter in.txt word out.txt
I get
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at wordfilter.main(wordfilter.java:42)
What's the problem? It's because of some difference on linux?
You're mixing line and token based functions, :hasNextLine() and next(). If the input ends with a line feed (typical on Linux) hasNextLine returns true at the end of the file, but there is no next "item".
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
You should use either hasNext with next, or hasNextLine with nextLine, mixing them is confusing.
while (scanner.hasNext()) {
lettura[i] = scanner.next();
i++;
}
The input file ends in a newline on Linux. Therefore, there's another line, but it's empty. If you remove the final newline from the input, the program will start working normally.
Or, import the exception
import java.util.NoSuchElementException;
and ignore it int the code
while (scanner.hasNextLine()) {
System.out.println("" + i);
try {
lettura[i] = scanner.next();
} catch (NoSuchElementException e) {}
i++;
}

split and store HTML tags into Arraylist

I'm trying to regenerate the English web page into Sinhala content.Currently i did part of it. When user enter the url it will load the html page of particular webpage and it will appear as line by line with html tags. but now i want to split html tags and content separately and store them in a array list separately.My full code is given below. Can anyone give an answer to split html tags and content separately and store them into array list.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.String;
public class Utils {
public static void main(String[] args) {
String url;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the url:");
url = sc.nextLine();
try {
System.setProperty("http.proxyHost", "cache.mrt.ac.lk");
System.setProperty("http.proxyPort", "3128");
//Document doc = Jsoup.connect(url).timeout(10000).get();
URL link = new URL("http://www.nlpu.com/NewDesign/NLPU_WhatIsNLP.html");
BufferedReader in = new BufferedReader(newht InputStreamReader(link.openStream()));
String inputLine;
String []arr;
int count=0;
while ((inputLine = in.readLine()) != null) {
// Process each line.
System.out.println("Line no :"+count++);
//for(int i=0;i<inputLine.length();i++){
ArrayList<String> list = new ArrayList<String>();
list.add(inputLine);
System.out.println();
//}
for(int i=0;i<list.size();i++){
System.out.println("got: "+list.get(i));
}
// inputLine = inputLine.replaceAll("\\<.*?\\>", "");
arr = inputLine.split("<.*?.>");
for(String ss:arr){
System.out.print("splitted : "+ss+" ");
}
System.out.println();
// System.out.println(arr[]);
//System.out.println(arr[2]);
//String s1=("මම බත් කමි");
//list.set(0,s1);
// System.out.println(""+list);
}
in.close();
}catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}//end main
private static String inputLine(int i) {
// TODO Auto-generated method stub
return null;
}
}
.
Based on my understanding, you can use a hashmap to store tag and content pair. The HashMap will have string as the key and arraylist as the value.
And for getting the tag, you can use something like inputLine.split(">") and get the first part.
Since there can be many tags with the same name, such as , you can add multiple values and add them into an arraylist and store them in a hashmap.
And one more thing to add, since you are reading the file line by line, it can happen that sometimes, you can have the ending tag in the next line. for eg...
I dont know how to put code in the editor
In such cases your program will not work. You can rather load the entire file in memory at once by using a RandomAccessFile and then write some algorithm to search for the ending tag.
I think it will help you. I just edited you code. Make sure its efficient way or not.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.String;
public class Utils {
public static void main(String[] args) {
String url;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the url:");
// url = sc.nextLine();
try {
System.setProperty("http.proxyHost", "cache.mrt.ac.lk");
System.setProperty("http.proxyPort", "3128");
//Document doc = Jsoup.connect(url).timeout(10000).get();
URL link = new URL("http://www.nlpu.com/NewDesign/NLPU_WhatIsNLP.html");
BufferedReader in = new BufferedReader(new InputStreamReader(link.openStream()));
String inputLine;
String[] arr;
int count = 0;
ArrayList<String> list1 = new ArrayList<String>();
while ((inputLine = in.readLine()) != null) {
// Process each line.
// System.out.println("Line no :" + count++);
//for(int i=0;i<inputLine.length();i++){
ArrayList<String> list = new ArrayList<String>();
list.add(inputLine);
//System.out.println();
//}
for (int i = 0; i < list.size(); i++) {
//System.out.println("got: " + list.get(i));
// inputLine = inputLine.replaceAll("\\<.*?\\>", "");
arr = inputLine.split("<.*?.>");
for (String ss : arr) {
list1.add(ss);
//System.out.print("splitted : " + ss + " ");
}
System.out.println();
// System.out.println(arr[]);
//System.out.println(arr[2]);
//String s1=("මම බත් කමි");
//list.set(0,s1);
// System.out.println(""+list);
}
}
for (String temp : list1) {
System.out.println("arrayed : " + temp + " ");
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}//end main
private static String inputLine(int i) {
// TODO Auto-generated method stub
return null;
}
}

Java Replace Line In Text File

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();
}
}

Find specific word in text file and count it

someone can help me with code?
How to search in text file any word and count how many it were repeated?
For example test.txt:
hi
hola
hey
hi
bye
hoola
hi
And if I want to know how many times are repeated in test.txt word "Hi" program must say "3 times repeated"
I hope you understood what I want, thank you for answers.
public int countWord(String word, File file) {
int count = 0;
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(word))
count++;
}
return count;
}
HashMap h=new HashMap();
FileInputStream fin=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(fin));
String n;
while((n=br.readLine())!=null)
{
if(h.containsKey(n))
{
int i=(Integer)h.get(n);
h.put(n,(i+1));
}
else
h.put(n, 1);
}
now iterate through this map to get the count for each word using each word as a key to the map values
Apache Commons - StringUtils.countMatches()
Use MultiSet collection from google guava library.
Multiset<String> wordsMultiset = HashMultiset.create();
Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
wordsMultiset.add(scanner.nextLine());
}
for(Multiset.Entry<String> entry : wordsMultiset ){
System.out.println("Word : "+entry.getElement()+" count -> "+entry.getCount());
}
package File1;
import java.io.BufferedReader;
import java.io.FileReader;
public class CountLineWordsDuplicateWords {
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br =null;
String [] stringArray;
int counLine = 0;
int arrayLength ;
String s="";
String stringLine="";
try{
fr = new FileReader("F:/Line.txt");
br = new BufferedReader(fr);
while((s = br.readLine()) != null){
stringLine = stringLine + s;
stringLine = stringLine + " ";/*Add space*/
counLine ++;
}
System.out.println(stringLine);
stringArray = stringLine.split(" ");
arrayLength = stringArray.length;
System.out.println("The number of Words is "+arrayLength);
/*Duplicate String count code */
for (int i = 0; i < arrayLength; i++) {
int c = 1 ;
for (int j = i+1; j < arrayLength; j++) {
if(stringArray[i].equalsIgnoreCase(stringArray[j])){
c++;
for (int j2 = j; j2 < arrayLength; j2++) {
stringArray[j2] = stringArray[j2+1];
arrayLength = arrayLength - 1;
}
}//End of If block
}//End of Inner for block
System.out.println("The "+stringArray[i]+" present "+c+" times .");
}//End of Outer for block
System.out.println("The number of Line is "+counLine);
System.out.println();
fr.close();
br.close();
}catch (Exception e) {
e.printStackTrace();
}
}//End of main() method
}//End of class CountLineWordsDuplicateWords
package somePackage;
public static void main(String[] args) {
String path = ""; //ADD YOUR PATH HERE
String fileName = "test2.txt";
String testWord = "Macbeth"; //CHANGE THIS IF YOU WANT
int tLen = testWord.length();
int wordCntr = 0;
String file = path + fileName;
boolean check;
try{
FileInputStream fstream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while((strLine = br.readLine()) != null){
//check to see whether testWord occurs at least once in the line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if(check){
//get the line, and parse its words into a String array
String[] lineWords = strLine.split("\\s+");
for(String w : lineWords){
//first see if the word is as least as long as the testWord
if(w.length() >= tLen){
/*
1) grab the specific word, minus whitespace
2) check to see whether the first part of it having same length
as testWord is equivalent to testWord, ignoring case
*/
String word = w.substring(0,tLen).trim();
if(word.equalsIgnoreCase(testWord)){
wordCntr++;
}
}
}
}
}
System.out.println("total is: " + wordCntr);
//Close the input stream
br.close();
} catch(Exception e){
e.printStackTrace();
}
}
public class Wordcount
{
public static void main(String[] args)
{
int count=0;
String str="hi this is is is line";
String []s1=str.split(" ");
for(int i=0;i<=s1.length-1;i++)
{
if(s1[i].equals("is"))
{
count++;
}
}
System.out.println(count);
}
}
You can read text file line by line. I assume that each line can contain more than one word. For each line, you call:
String[] words = line.split(" ");
for(int i=0; i<words.length; i++){
if(words[i].equalsIgnoreCase(searhedWord))
count++;
}
try using java.util.Scanner.
public int countWords(String w, String fileName) {
int count = 0;
Scanner scanner = new Scanner(inputFile);
scanner.useDelimiter("[^a-zA-Z]"); // non alphabets act as delimeters
String word = scanner.next();
if (word.equalsIgnoreCase(w))
count++;
return count;
}
Try it this way with Pattern and Matcher.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Dem {
public static void main(String[] args){
try {
File f = new File("d://My.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = new String();
while((s=br.readLine())!=null){
s = s + s;
}
int count = 0;
Pattern pat = Pattern.compile("it*");
Matcher mat = pat.matcher(s);
while(mat.find()){
if(mat.find()){
mat.start();
count++;
}
}
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.util.*;
class filedemo
{
public static void main(String ar[])throws Exception
BufferedReader br=new BufferedReader(new FileReader("c:/file.txt"));
System.out.println("enter the string which you search");
Scanner ob=new Scanner(System.in);
String str=ob.next();
String str1="",str2="";
int count=0;
while((str1=br.readLine())!=null)
{
str2 +=str1;
}
int index = str2.indexOf(str);
while (index != -1) {
count++;
str2 = str2.substring(index + 1);
index = str2.indexOf(str);
}
System.out.println("Number of the occures="+count);
}
}
package com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception{
BufferedReader bf= new BufferedReader(new FileReader("src/test.txt"));
Scanner sc = new Scanner(System.in);
String W=sc.next();
//String regex ="[\\w"+W+"]";
int count=0;
//Pattern p = Pattern.compile();
String line=bf.readLine();
String s[];
do
{
s=line.split(" ");
for(String a:s)
{
if(a.contains(W))
count++;
}
line=bf.readLine();
}while(line!=null);
System.out.println(count);
}
}
public int occurrencesOfHi()
{
String newText = Text.replace("Hi","");
return (Text.length() - newText.length())/2;
}

Categories

Resources