Replace a String from Array to Line in File - java

My file has:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
The code below does the following.
1. If line count equals num[index],it checks whether if that line contains the string from
VALUES1[index]. If true, it replace that string from the first index in VALUES[index] and writes to a new file.
2.If num index not equal num[index],it simply writes the line to new file as it is.
The problem am getting is that after writing to new file, original line 1 and 2 still appears in the new file. How to remove that.
Heres my code:
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {1,2,4}; //Line Numbers
String[] VALUES = new String[] {"AB","BC","CD"}; //Correct Solutions
String[] VALUES1 = new String[] {"class","void","System"}; //To Replace
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
String line1 = null;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
if(line.contains(VALUES1[index])){
line1= line.replace(VALUES1[index], VALUES[index]);
writer1.write(line1+System.getProperty("line.separator"));
}
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
Here is my result:
public AB MyC{
**public class MyC{ //This still appears.**
public BC MyMethod()
**public void MyMethod()//This still appears.**
{
CD.out.println("My method has been accessed");
System.out.println("My method has been accessed");
System.out.println("hi");
}
}

you should add an indicator to show if this line is replaced
while(line!=null){
boolean exists = false;
for(int index =0;index<num.length;index++){
if(count == num[index]){
if(line.contains(VALUES1[index])){
exists = true;
line1= line.replace(VALUES1[index], VALUES[index]);
writer1.write(line1+System.getProperty("line.separator"));
}
}
}
if (!exists)
writer1.write(line+System.getProperty("line.separator"));

comment this line in code
writer1.write(line+System.getProperty("line.separator"));
then try

Related

How to read every line after :

I have a TXT file like this:
Start: Here is a random introduction.
Items:
Item 1
Item 2
Item 3
Item 4
End: Here is a random outro.
I want to retrieve Item 1, Item 2, Item 3, Item 4 and put them into a data structure like a HashMap. How can I achieve this?
Here is what I've tried so far:
public static void main(String[] args) {
Scanner scanner = null;
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("Start:")) {
String time = line.substring(6);
}
if (line.matches("Items:") && scanner.hasNextLine()) {
String items = line;
}
}
}
[Updated Answer] So the other answer on this question is helpful if the exact words are know that are to be ignored but when there is a big file with lot of lines than this solution will be more accurate.
public static void main(String[] args) {
// TODO Auto-generated method stub
String line = "";
String[] parts = null;
HashMap<String, String> hashmap=new HashMap<String, String>();
try {
BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
//line = br.readLine();
while (line != null) {
line = br.readLine();
//System.out.println(line.toString());
if(line!=null){
//System.out.println(line);
if(line.contains("Item")&& line.substring(0, 5).compareTo("Item ")==0){
addToHashMap(line,hashmap);
System.out.println(line);
}
}
}
br.close();
}catch(IOException ioe){
System.err.println(ioe.getMessage());
}
}
private static void addToHashMap(String line, HashMap<String,String> hashMap) {
// TODO Auto-generated method stub
Random random=new Random();
hashMap.put(Integer.toString(random.nextInt(100)), line);
}
The following code should work:
public static void main(String[] args) {
Scanner scanner = new Scanner(TestCdllLogger.class.getResourceAsStream("/test.txt"));
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("Start:") || line.startsWith("End:") || line.startsWith("Items:") || line.startsWith(" ") ||line.isEmpty() ) {
continue;
}
System.out.println(line);
}
}
it ignores all lines starts with Start:, End:, Items: and blank or emty lines.
I know that the code write the lines to stdout and not to a file, but this can changed by your own

How I can to skip some area of text, when reading file?

I reading a .txt file and want to skip a listing of code in this text, when putting result in StringBuilder.
The example of text:
The following Bicycle class is one possible implementation of a
bicycle:
/* The example of Bicycle class class Bicycle {
int cadence = 0;
int speed = 0; } */
So that's what I could come to:
public class Main {
public static BufferedReader in;
public static StringBuilder stringBuilder = new StringBuilder();
public static void main(String[] args) {
String input = "input_text.txt";
try {
in = new BufferedReader(new FileReader(input));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String inputText;
try {
while ((inputText = in.readLine()) != null) {
if (inputText.startsWith("/*")) {
// The problem is there:
while (!inputText.endsWith("*/")) {
int lengthLine = inputText.length();
in.skip((long)lengthLine);
}
}
stringBuilder.append(inputText);
}
} catch (IOException e) {
e.printStackTrace();
}
I got the infinity while loop and can't jump to next line.
You never reset the value of inputText in your while loop, so it will never not end with */ resulting in an infinite loop. Also you don't need to use the skip() method as simply reading the lines until you encounter a */ will work. Try changing your loop to:
while (!inputText.endsWith("*/")) {
String temp = in.readLine();
if(temp == null) {break;}
inputText = temp;
}
Output: (With printing the StringBuilder)
The following Bicycle class is one possible implementation of a bicycle:

How do I get my InputStream to give me lines as a String array?

I have process and got an InputStream like:
myInputStream = getProcess().getInputStream();
I would like to somehow like to beable to call these methods
String[] getLines(int start, int stop); // Will return a String array of those lines
String[] getLines(int start); // Will return a String array of lines from the line number to the end
String[] getLines(); //Returns the entire output as an array seperated by the end of the line.
Also I will have several processes running at once so storing the entire logs in memory the entire time wouldn't be the best I think.
The Scanner class may be of help here since it can read lines from an InputStream. Note that I provided a simple test case to verify the contents.
I agree with #LouisWasserman's comment that InputStreams aren't really suitable for this but the following may work.
public class LogReaderTest {
public static class LogReader {
private final Scanner scanner;
public LogReader(final InputStream stream) {
scanner = new Scanner(stream);
}
public String[] getLines(int start, int stop) {
fastForward(start);
int stopVal = stop <= start ? Integer.MAX_VALUE : stop - start;
final List<String> rows = new ArrayList<>();
for (int i = 0; i < stopVal; i++) {
if (scanner.hasNextLine()) {
rows.add(scanner.nextLine());
} else {
break;
}
}
return rows.toArray(new String[rows.size()]);
}
public String[] getLines(int start) {
return getLines(start, -1);
}
public String[] getLines() {
return getLines(0);
}
private void fastForward(final int lines) {
for (int i = 0; i < lines; i++) {
if (scanner.hasNextLine()) {
scanner.nextLine();
} else {
throw new IllegalStateException("Unable to scan line");
}
}
}
}
#Test
public void testLogReader() throws IOException {
final String[] lines = {"first", "second", "third", "fourth"};
final String stringWithNewLines = Arrays.stream(lines).collect(Collectors.joining("\n"));
Assert.assertEquals(
4, new LogReader(
new ByteArrayInputStream(stringWithNewLines.getBytes())).getLines().length);
Assert.assertEquals(
2, new LogReader(
new ByteArrayInputStream(stringWithNewLines.getBytes())).getLines(2).length);
Assert.assertEquals(
3, new LogReader(
new ByteArrayInputStream(stringWithNewLines.getBytes())).getLines(1, 4).length);
}
}
Use BufferedReader to read InputStream line by line. try this code or you can implement your own logic.
String[] getLines(){
return getLines(0,0);
}
String[] getLines(int start){
return getLines(start,0);
}
String[] getLines(int start,int stop){
ArrayList<String> list = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new
InputStreamReader(myInputStream));
String line;
Integer count=1;
try {
while ((line = reader.readLine()) != null) {
if(count>=start){
if(stop==0 || count<=stop)
list.add(line);
}
count++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return list.toArray(new String[list.size()]);
}

Java matching a given word with combinations of same size

I have almost managed to accomplish this but not to the full. So what I need is for example I give the word DOG and the program will look into a text file and return DOG and GOD, i.e words that can be generated by the odds given only. My code is giving me all words that contain 'D', 'O' and 'G'. My code is this:
public class JavaReadTextFile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ReadFile rf = new ReadFile();
String filename = "/Users/Elton/Desktop/OSWI.txt";
String wordinput;
String wordarray[] = new String[1];
System.out.println("Input Characters: ");
wordinput = input.nextLine();
wordarray[0] = wordinput;
System.out.println(wordinput.length());
try {
String[] lines = rf.readLines(filename);
for (String line : lines) {
if (line.matches(wordarray[0] + ".*")) {
System.out.println(line);
}
}
} catch (IOException e) {
System.out.println("Unable to create " + filename + ": " + e.getMessage());
}
}
}
----- then i have:
public class ReadFile {
String [] cName = new String [100];
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null ) {
cName[0] = line.split(" ")[0];
lines.add(cName[0]);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
I can see you are able to read the words from file. Rest of the work is simple. algorithm will be something like this
sort inputWord
sort the word you read from file
if both word is same print or add it to some list.
And here is simple demonstration of above algorithm you can modify it to your need.
public class App {
static String sortString (String str) {
char []chars = str.toCharArray();
sort(chars);
return new String(chars);
}
public static void main(String... args) {
String inputWord = "DoG";
String readWord = "God";
inputWord = inputWord.toUpperCase();
readWord = readWord.toUpperCase();
inputWord = sortString(inputWord);
readWord = sortString(readWord);
if(inputWord.equalsIgnoreCase(readWord)) {
System.out.println(readWord);// you can add it to your list
}
}
}
If I understand you correctly, you want to display all the anagrams of a word?
Change your method readLines() to return an ArrayList instead of an array.
ArrayList<String> readLines(String fname) {
File file = new File(fname);
ArrayList<String> list = null;
try {
Scanner scanner = new Scanner(file);
list = new ArrayList<String>();
while (scanner.hasNext()) {
String currentWord = scanner.next();
if (!currentWord.isEmpty()) {
list.add(currentWord);
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return list;
}
The use this function with input parameter dictionary being the ArrayList you return from readLines. The function uses the fact that two anagrams like "DOG" and "GOD" are equal strings when both are sorted (i.e. "DGO" equals "DGO")
public ArrayList<String> getAnagrams(String word, ArrayList<String> dictionary) {
if(word == null || dictionary == null) {
return null;
}
ArrayList<String> anagrams = new ArrayList<String>();
char[] sortedChars = word.toCharArray();
Arrays.sort(sortedChars);
for(String item : dictionary) {
char[] sortedDictionaryItem = item.toCharArray();
Arrays.sort(sortedDictionaryItem);
if(Arrays.equals(sortedChars, sortedDictionaryItem)) {
anagrams.add(item);
}
}
return anagrams;
}
If you don't like the changes I am suggesting, you can also do the following. In the loop where you do:
if (line.matches(wordarray[0] + ".*")) {
System.out.println(line);
}
You can check if the two strings are permutations of each other:
if (isPermutation(line, wordarray[0]) {
System.out.println(line);
}
By adding these two functions:
String sortString(String s) {
char[] chars = s.toCharArray();
java.util.Arrays.sort(chars);
return new String(chars);
}
boolean isPermutation(String s1, String s2) {
if(s1.length() != s2.length()) {
return false;
}
s1 = sortString(s1);
s2 = sortString(s2);
return (s1.compareTo(s2) == 0);
}
This may help you adapt your code.
import java.util.regex.* ;
public class Find_Dogs_And_Gods
{
public static void main(String []args)
{
String line = "2ldoghmDoggod" ;
Pattern p = Pattern.compile("[d,D,g,G][o,O][d,D,g,G]") ;
Matcher m = p.matcher(line) ;
while(m.find() )
{
System.out.println( m.group() ) ;
}
}
}

reading file StringTokenizer to int

I have create the following program and I am little stuck here.
Here is the code:
class ProductNameQuan{
public static void main(String[] args)
{
String fileName = "stockhouse.txt";
StringTokenizer line;
String ProdName;
String quantity;
try {
BufferedReader in = new BufferedReader(new FileReader(fileName));
line = in.readLine();
while (line != null) {
ProdName = line.nextToken();
quantity = line.nextToken();
System.out.println(line);
line = in.readLine();
}
in.close();
} catch (IOException iox)
{
System.out.println("Problem reading " + fileName);
}
}
}
I am trying to find the way to read from the file the first 10 information's through the array (not arraylist)ProdName and the quantity." plus that I stack in the in.readLine(); propably is not compatible with the StringTokenizer.
Now the other problem is that I need the quantity to be an integer instead of string.
The file includes something like that:
Ball 32
tennis 322
fireball 54
..
.
.
.
.
Any ideas?
I would place this in a helper function, maybe called parseString
class ProductNameQuan {
public static void main(String[] args)
{
...
try {
BufferedReader in = ...
line = in.readLine();
while (line != null) {
ProductNameQuan.parseString(line);
}
}
...
}
public static void parseString(String someString)
{
StringTokenizer st = new StringTokenizer(someString);
while (st.hasMoreTokens()) {
String token = line.nextToken();
try {
int quantity = Integer.parseInt(token)
// process number
} catch(NumberFormatException ex) {
// process string token
}
}
}

Categories

Resources