Replace lines in File with another string - java

I have a text file with the following contents:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
I have an array num[]= {2,3,4}; which contains the line numbers to be completely replaced with the strings from this array
String[] VALUES = new String[] {"AB","BC","CD"};
That is line 2 will be replaced with AB, line 3 with BD and ine 4 with CD.
Lines which are not in the num[]array have to be written to a new file along with the changes made.
I have this so far.I tried several kind of loops but still it does not work.
public class ReadFileandReplace {
/**
* #param args
*/
public static void main(String[] args) {
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
int l = num.length;
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
LineNumberReader reader = new LineNumberReader(br);
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
int count =0;
line = br.readLine();
count++;
while(line!=null){
System.out.println(count+": "+line);
line = br.readLine();
count++;
int i=0;
if(count==num[i]){
int j=0;;
System.out.println(count);
String newtext = line.replace(line, VALUES[j]) + System.lineSeparator();
j++;
writer1.write(newtext);
}
i++;
writer1.append(line);
}
writer1.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
The expected output should look like this:
public class MyC{
AB
BC
CD
Sys.out.println("hi");
}
}
When I run the code, all lines appear on the same line.

You've done almost, I've updated your code with a map. Check this
int num[] = {3, 4, 5};
String[] values = new String[]{"AB", "BC", "CD"};
HashMap<Integer,String> lineValueMap = new HashMap();
for(int i=0 ;i<num.length ; i++) {
lineValueMap.put(num[i],values[i]);
}
FileInputStream fs = new FileInputStream("test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("test1.txt");
int count = 1;
String line = br.readLine();
while (line != null) {
String replaceValue = lineValueMap.get(count);
if(replaceValue != null) {
writer1.write(replaceValue);
} else {
writer1.write(line);
}
writer1.write(System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.flush();

You're appending each line to the same string. You should add the line separator character at the end of each line as well. (You can do this robustly using System.getProperty("line.separator"))

you have not appended end line character.
writer1.append(line); is appending the data in line without endline character. Thus it is showing in one line. You might need to change it to:
writer1.append(line).append("\n");

Try This
package src;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
FileInputStream fs= new FileInputStream("C:\\Test\\ren.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Test\\ren1.txt");
String line;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
line = VALUES[index];
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}

Related

Read a file containing multiple entries and output one entry based on user input

I am new to java and this might sound really stupid but !
Assume you have this txt file somewhere in your pc
The_txt.txt
Anthony
anthonyk#somewhere.com
01234567891
location
Maria
maria#somewhere.com
1234561234
location2
George
george#somewhere.com
1234512345
location3
What i want to do with this txt is that , I prompt the user to insert a Phone number so if for example the user provides Maria's phone number (1234561234) the program will output
Maria
maria#somewhere.com
1234561234
location2
My piece of code for this task :
private static void Search_Contact_By_Phone(File file_location){
Scanner To_Be_String = new Scanner(System.in);
String To_Be_Searched = To_Be_String.nextLine();
System.out.println("\n \n \n");
BufferedReader Search_Phone_reader;
try {
Search_Phone_reader = new BufferedReader(new FileReader (file_location));
String new_line = Search_Phone_reader.readLine();
while (new_line != null) {
if (To_Be_Searched.equals(new_line)){
for (int i=0;i<=3;i++){
System.out.println(new_line);
new_line = Search_Phone_reader.readLine();
}
break;
}
new_line = Search_Phone_reader.readLine();
}
Search_Phone_reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Thank you in advance!!!
package com.mycompany.io;
import java.io.BufferedReader;
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.List;
public class Main {
public static void main(String[] args) throws IOException {
// For a small file
Path path = Paths.get("The_txt.txt");
String toBeSearched = "1234512345";
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// Better performance if i starts at 2 and i += 4
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).equals(toBeSearched)) {
System.out.println(lines.get(i - 2));
System.out.println(lines.get(i - 1));
System.out.println(lines.get(i));
System.out.println(lines.get(i + 1));
}
}
// Else
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line1;
while ((line1 = reader.readLine()) != null) {
String line2 = reader.readLine();
String line3 = reader.readLine();
if (line3.equals(toBeSearched)) {
// Found
System.out.println(line1);
System.out.println(line2);
System.out.println(line3);
System.out.println(reader.readLine());
break;
} else {
reader.readLine();
}
}
}
}
}

How to add a column to CSV which consists of data in Java

Can we add a new column to CSV as the last column which already has let's say 3 columns with some data in it? So this new one will be added later as 4th column moreover for every row it should have random numbers.
Example,
Id Name Address Calculated
1 John U.K. 341679
2 Vj Aus 467123
3 Scott U.S. 844257
From what I understand this will require first to read csv, for loop may be to iterate to the last column and then add a new calculated column i.e Write to csv. And to add values may be the Random class of Java. But how exactly can this be done is the real question. Like a sample code would be helpful.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Demo1 {
public static void main(String[] args) throws IOException {
String csvFile = "C:\\MyData\\Input.csv";
String line = "";
String cvsSplitBy = ",";
String newColumn = "";
List<String> aobj = new ArrayList<String>();
/* Code to read Csv file and split */
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null)
{
String[] csvData = line.split(cvsSplitBy);
int arrayLength = csvData.length;
}
}
/* Code to generate random number */
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
}
}
Great, so based on the code you provide, this could look like the following
(just to give you the idea - I write it here on the fly without testing...)
:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Demo1 {
//moved your random generator here
public static String getRandomNumber() {
/* Code to generate random number */
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
return finaldata;
}
public static void main(String[] args) throws IOException {
String csvFile = "C:\\MyData\\Input.csv";
String temporaryCsvFile = "C:\\MyData\\Output_temp.csv";
String line = "";
String cvsSplitBy = ",";
String newColumn = "";
List<String> aobj = new ArrayList<String>();
/* Code to read Csv file and split */
BufferedWriter writer = new BufferedWriter(new FileWriter(
temporaryCsvFile));
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null)
{
//String[] csvData = line.split(cvsSplitBy);
//int arrayLength = csvData.length;
//actually you don't even need to split anything
String newFileLine = line + cvsSplitBy + getRandomNumber();
// ... We call newLine to insert a newline character.
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
//Now delete the old file and rename the new file
//I'll leave this to you
}
}
Based on #Plirkee sample code and his help I made a final working code. Sharing it here so that it might be useful for someone with a similar requirement.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Demo1 {
public static String getRandomNumber() {
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) // length of the random string.
{
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
return finaldata;
}
public static void main(String[] args) throws IOException {
File sourceCsvFile = null;
File finalCsvFile = null;
// String sourceCsvFileName = "";
sourceCsvFile = new File("C:\\MyData\\Input.csv");
finalCsvFile = new File("C:\\MyData\\Input_1.csv");
String line = "";
String cvsSplitBy = ",";
BufferedWriter writer = new BufferedWriter(new FileWriter(finalCsvFile));
try (BufferedReader br = new BufferedReader(new FileReader(sourceCsvFile))) // read the actual Source downloaded csv file
{
line = br.readLine(); // read only first line
String newFileLine = line + cvsSplitBy + "HashValue"; // append "," and new column <HashValue>
writer.write(newFileLine); // will be written as first line in new csv
writer.newLine(); // go to next line for writing next lines
while ((line = br.readLine()) != null) // this loop to write data for all lines except headers
{
newFileLine = line + cvsSplitBy + getRandomNumber(); // will add random numbers for each row
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
if(finalCsvFile.exists() && finalCsvFile.length() > 0)
{
System.out.println("New File with HashValue column created...");
if(sourceCsvFile.delete())
{
System.out.println("Old File deleted successfully...");
}
else
{
System.out.println("Failed to delete the Old file...");
}
}
else if (!finalCsvFile.exists())
{
System.out.println("New File with HashValue column not created...");
}
}
}

I am trying to count characters from a within file

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

Reading data from a text file in Java

I have a problem in reading data from a text file and put it in 2 dimensional array. The sample of dataset is:
1,2,3,4,5,6
1.2,2.3,4.5,5.67,7.43,8
The problem of this code is that it just read the first line and does not read the next lines. Any suggestion is appreciated.
package test1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test1{
public static void main(String args[])throws FileNotFoundException, IOException{
try{
double[][] X = new double[2][6];
BufferedReader input = new BufferedReader(new FileReader(file));
String [] temp;
String line = input.readLine();
String delims = ",";
temp = line.split(delims);
int rowCounter = 0;
while ((line = input.readLine())!= null) {
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
rowCounter++;
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
}
}
}
Have you tried the Array utilities? Something like this:
while ((line = input.readLine())!= null) {
List<String> someList = Arrays.asList(line.split(","));
//do your conversion to double here
rowCounter++;
}
I think the blank line might be throwing your for loop off
The only place that your temp array is being assigned is before your while loop. You need to assign your temp array inside the loop, and don't read from the BufferedReader until the loop.
String[] temp;
String line;
String delims = ",";
int rowCounter = 0;
while ((line = input.readLine())!= null) {
temp = line.split(delims); // Moved inside the loop.
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
Try:
int rowCounter = 0;
while ((line = input.readLine())!= null) {
String [] temp;
String line = input.readLine();
String delims = ",";
temp = line.split(delims);
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
...
readLine expects a new line character at the end of the line. You should put a blank line to read the last line or use read instead.
I couldn't run the code, but one of your problems is that you were only splitting the first text line.
package Test1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test1 {
public static void main(String args[]) {
try {
double[][] X = new double[2][];
BufferedReader input = new BufferedReader(new FileReader(file));
String line = null;
String delims = ",";
int rowCounter = 0;
while ((line = input.readLine()) != null) {
String[] temp = line.split(delims);
for (int i = 0; i < temp.length; i++) {
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
rowCounter++;
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
}
}
}
I formatted your code to make it more readable.
I deferred setting the size of the second element of the two dimensional array until I knew how many numbers were on a line.

How to read last 5 lines of a .txt file into java

I have a text file that consists of several entries such as:
hello
there
my
name
is
JoeBloggs
How would I read the last five entries in descending order, i.e. from JoeBloggs - there
I currently have code to read the LAST LINE only:
public class TestLastLineRead {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream(file.txt);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null, tmp;
while ((tmp = br.readLine()) != null) {
strLine = tmp;
}
String lastLine = strLine;
System.out.println(lastLine);
in.close();
}
}
You can add the lines to a List, e.g. a LinkedList. When the list has more than five lines, remove the first/last.
List<String> lines = new LinkedList<String>();
for(String tmp; (tmp = br.readLine()) != null;)
if (lines.add(tmp) && lines.size() > 5)
lines.remove(0);
One very easy way would be to use the CircularFifoBuffer class from the Apache Commons Collections library. It's basically a list of a fixed size that discards old elements when it's full and you add new ones. So you'd create a CircularFifoBuffer of size 5, then add all the lines to it. At the end, it'd contain just the last five lines of the file.
we can use MemoryMappedFile for printing last 5 lines:
private static void printByMemoryMappedFile(File file) throws FileNotFoundException, IOException{
FileInputStream fileInputStream=new FileInputStream(file);
FileChannel channel=fileInputStream.getChannel();
ByteBuffer buffer=channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
buffer.position((int)channel.size());
int count=0;
StringBuilder builder=new StringBuilder();
for(long i=channel.size()-1;i>=0;i--){
char c=(char)buffer.get((int)i);
builder.append(c);
if(c=='\n'){
if(count==5)break;
count++;
builder.reverse();
System.out.println(builder.toString());
builder=null;
builder=new StringBuilder();
}
}
channel.close();
}
RandomAccessFile to print last 5 lines:
private static void printByRandomAcessFile(File file) throws FileNotFoundException, IOException{
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
int lines = 0;
StringBuilder builder = new StringBuilder();
long length = file.length();
length--;
randomAccessFile.seek(length);
for(long seek = length; seek >= 0; --seek){
randomAccessFile.seek(seek);
char c = (char)randomAccessFile.read();
builder.append(c);
if(c == '\n'){
builder = builder.reverse();
System.out.println(builder.toString());
lines++;
builder = null;
builder = new StringBuilder();
if (lines == 5){
break;
}
}
}
}
Try this code, a list of length 5 is scanned through all the lines, finally the list is reversed. I edited / modified your code, test it to see it's fully working.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Test
{
public static void main(String[] args) throws Exception
{
ArrayList<String> bandWidth = new ArrayList<String>();
FileInputStream in = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String tmp;
while ((tmp = br.readLine()) != null)
{
bandWidth.add(tmp);
if (bandWidth.size() == 6)
bandWidth.remove(0);
}
ArrayList<String> reversedFive = new ArrayList<String>();
for (int i = bandWidth.size() - 1; i >= 0; i--)
reversedFive.add(bandWidth.get(i));
in.close();
}
}
If all it really does have to do is print last 5 lines:
ArrayList<String> lines = new ArrayList<String>();
String tmp="";
while ((tmp = br.readLine()) != null) {
lines.add(tmp);
}
for (int i = lines.size()-5; i < lines.size(); i++) {
System.out.println(lines.get(i-1));
}
First you have to read the file line by line and add each line to a list. Once the file is read completely, you can print each element in the list in reverse order as shown below:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class FileReader {
public static List<String> readFile() throws IOException {
List<String> fileContents = new ArrayList<String>();
FileInputStream fileInputStream = new FileInputStream("C:/Users/compaq/Desktop/file.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String strLine = null;
while((strLine=bufferedReader.readLine())!=null) {
fileContents.add(strLine);
}
fileInputStream.close();
return fileContents;
}
public static void printFileInReverse(List<String> fileContents, int numberOfLines) {
int counter = 0;
for(int i=(fileContents.size()-1);i>=0;i--) {
if(counter==numberOfLines) { break; }
System.out.println(fileContents.get(i));
counter++;
}
}
public static void main(String[] args) throws IOException {
List<String> fileContents = new ArrayList<String>();
fileContents = FileReader.readFile();
int numberOfLines = 5;// Number of lines that you would like to print from the bottom of your text file.
FileReader.printFileInReverse(fileContents, numberOfLines);
}
}
Try this.
This give for last 5 line.
public static void main(String[] args) throws IOException {
List<String > list =new ArrayList<String>();
FileInputStream in = new FileInputStream("C:/adminconsole.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine ="", tmp;
while ((tmp = br.readLine()) != null){
//strLine =tmp+"\n"+strLine;
list.add(tmp);
}
if(list.size()>5){
for (int i=list.size()-1; i>=(list.size()-5); i--) {
System.out.println(list.get(i));
}
}else{
for (int i=0; i<5; i++) {
System.out.println(list.get(i));
}
}
}
}
Follow This Code To Improve Core Java Logic By Using Collectios.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
public class REVERSE {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
try {
Scanner sc = new Scanner(new FileReader("input.txt"));
while (sc.hasNextLine()) {
al.add(sc.nextLine());
}
System.out.println(al.get(0));
System.out.println(al.get(1));
System.out.println(al.get(2));
System.out.println(al.get(3));
System.out.println(al.get(4));
Collections.reverse(al);
/*
* for (String s : al) { System.out.println(s); }
*/
System.out.println(al.get(0));
System.out.println(al.get(1));
System.out.println(al.get(2));
System.out.println(al.get(3));
System.out.println(al.get(4));
/*
* for (int i = 0; i < al.size(); i++) {
* System.out.println(al.get(i)); }
*/
} catch (FileNotFoundException e) {
}
}
}
Please try this code. It is working fine for me.
public static void main(String[] args)
{
try
{
int numOfLastline = 10;
BufferedReader reader = new BufferedReader(new FileReader("Text.txt"));
int lines = 0;
while (reader.readLine() != null)
lines++;
reader.close();
System.out.println(lines);
String printedLine = null;
List<String> listForString = new ArrayList<String>();
for (int i = lines - 1; i >= (lines - numOfLastline); i--)
{
printedLine = (String) FileUtils.readLines(new File("Text.txt"), "ISO-8859-1").get(i);
System.out.println(printedLine);
listForString.add(printedLine);
}
System.out.println("\n\n============ Printing in Correct order =============\n\n");
Collections.reverse(listForString);
for (int k = 0; k < listForString.size() ; k++)
{
System.out.println(listForString.get(k));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Note : Provide your needed last line numbers at numOfLastline and file [instead of this Text.txt].

Categories