Replace Pattern match with Preferred Text Java - java

Hey I am trying to replace the a regex pattern in a directory of files and replace with this character 'X'. I started out trying alter one file but that is not working. I cam eup with the following code any help would be appreciated.
My goal is to read all the file content find the regex pattern and replace it.
Also this code is not working it runs but dose nothing to the text file.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class DataChange {
public static void main(String[] args) throws IOException {
String absolutePathOne = "C:\\Users\\hoflerj\\Desktop\\After\\test.txt";
String[] files = { "test.txt" };
for (String file : files) {
File f = new File(file);
String content = FileUtils.readFileToString(new File(absolutePathOne));
FileUtils.writeStringToFile(f, content.replaceAll("2018(.+)", "X"));
}
}
}
File Content inside the file is:
3-MAAAA2017/2/00346
I am trying to have it read through and replace 2017/2/00346 with XXX's
my goal is to do this for like 3 files at one time also.

Related

Create new file with the contents of a string array taken from another file using methods (Java)

I am writing some code that takes each line of a txt file and stores it into a string. Afterward, the program will make a new file and store write the array into it.
This is the contents of the file:
04/26/16 Sega 3D Classics Collection
07/14/16 Batman: Arkham Underworld
06/24/16 Tokyo Mirage Sessions #FE
The problem with my code is that it doesn't seem to store or make a new file once the method is running. The method to make the file into a string array works but it doesn't seem to take that array and write it on a brand new file. What I have tried is to use the FileWriter function to make a new file on my computer and use the writer function to write the array onto the file. Whenever I run or debug the program there is no new file in my computer.
This is the code I have:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main (String[]args) throws FileNotFoundException{
File file = new File("releasedates.txt");
input(file);
}
public static String[]input (File file) throws FileNotFoundException{
String[]arr = new String[3];
Scanner sc = new Scanner(file);
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextLine();
}
return arr;
}
public static void output(String filename, String[] info) throws IOException{
FileWriter writer = new FileWriter("fileName.txt");
writer.write(filename);
writer.close();
}
}
If you're hoping that running your main() method will read and write back out the contents of the file I'm seeing the following things that are preventing you from having the result you're looking for:
Your main() never calls the output() method that actually writes to the file.
Your output() method will write the value of fileName to the file, not the value of the info array that you pass in. You may have to call Arrays.toString(info) or iterate through its contents so the FileWriter can process it correctly.

OCR implementation using using java

I have written java code to convert images into text using java.But my code is taking only single image as input . I want that the program should fetch images from a folder and then run the OCR on it.
My code is:
import java.io.FileOutputStream;
import org.bytedeco.javacpp.*;
import org.junit.Test;
import static org.bytedeco.javacpp.lept.*;
import static org.bytedeco.javacpp.tesseract.*;
import static org.junit.Assert.assertTrue;
import java.io.File;
public class BasicTesseractExampleTest {
#Test
public void givenTessBaseApi_whenImageOcrd_thenTextDisplayed() throws Exception {
BytePointer outText;
TessBaseAPI api = new TessBaseAPI();
// Initialize tesseract-ocr with English, without specifying tessdata path
if (api.Init(".", "ENG") != 0) {
System.err.println("Could not initialize tesseract.");
System.exit(1);
}
PIX image = pixRead("IMG_0012 (1).jpg");
api.SetImage(image);
// Get OCR result
outText = api.GetUTF8Text();
String string = outText.getString();
assertTrue(!string.isEmpty())
System.out.println(str);
// Destroy used object and release memory
api.End();
outText.deallocate();
pixDestroy(image);
}
}
To read a list of files out of a given Path use for example:
File f = new File("C:/programs");
File[] fileArray = f.listFiles();
Now you can check every File out of the fileArray if it is a directory and skip that with:
if(fileArray[0].isDirectory()) continue;
To find the images you can check for example the ending of the filename with:
fileArray[0].getName().endsWith(".jpg")
Do this check for all files out ouf the fileArray and call your method with the right files. To check the right file you have to change this line of your code:
PIX image = pixRead("IMG_0012 (1).jpg");
and add the fileArray[?] where the ? must be replaced with the right number.

generate excel file as output in Java

The following java code:
import java.io.File;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class extract
{
public static void main (String[] args) throws java.lang.Exception
{
String testData = new Scanner( new File("109.txt") ).useDelimiter("\\A").next();
//String testData = "#1|77|1391436891|1|1|00:1e:58:f4:15:f7|Nexus 4, 4.4, MAKOZ30d $1|1391436893 ?[176.08179, -13.839829, -1.0054213] %PKKV7|00:7f:28:3f:17:9d|-67|2437 %DC2VJ|f8:e4:fb:a0:06:f8|-71|2412 %VVWSP|00:7f:28:d5:92:65|-71|2462 %SVT8H|f8:e4:fb:8e:d6:9b|-77|2437 %ThreeBestFriends|20:10:7a:14:6a:f7|-66|2452 %2X4C8|00:7f:28:44:23:da|-75|2437 %STDGD|f8:e4:fb:70:86:f4|-82|2462 %DeathStar|00:7f:28:be:c8:94|-84|2412 %Freeinternet|00:1e:58:f4:15:f7|-59|2437 %QB657|00:26:62:b7:16:4b|-88|2462 %375F2|00:26:b8:3e:0a:14|-70|2412 %E1K38|00:26:62:cf:90:37|-81|2412";
String regularExpression = "\\w{2}:\\w{2}:\\w{2}:\\w{2}:\\w{2}:\\w{2}\\W{1}-\\d{2}";
Pattern pattern = Pattern.compile(regularExpression);
Matcher matcher = pattern.matcher(testData);
while(matcher.find()) {
System.out.println(matcher.group(0));
}
}
}
generates the following output:
00:1a:1e:87:04:42|-87
00:1a:1e:8e:e9:a2|-77
00:1a:1e:87:04:51|-95
00:1a:1e:84:92:02|-84
00:1a:1e:8d:f7:a2|-67
00:1a:1e:82:b8:e1|-56
00:1a:1e:82:b8:e2|-54
00:1a:1e:82:b8:e0|-56
00:1a:1e:87:04:41|-88
00:1a:1e:8d:f7:b1|-78
00:1a:1e:8d:f7:b2|-78
I'm trying to save output file as an excel file separated by columns.
Does anybody has any suggestions on how to achieve this?
Thank you!
Just add some commas (currently you don't have any), and save it as a text file named some_file_name.csv. You may use e.g. a BufferedWriter for this.
Saying 'Excel file separated by commas' is incorrect, actually the proper term is 'comma separated values file' or 'CSV file'. Programs other than Excel can open such files too.

Java reading file and storing text as array

I wrote a program someone told me to do for reading file and storing the text as an array, but when I run the program, I get an error that looks like this:
run:
Exception in thread "main" java.io.FileNotFoundException: KeyWestTemp.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.util.Scanner.<init>(Scanner.java:656)
at HeatIndex.main(HeatIndex.java:32)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
I want to have my program display the array to make sure it works correctly. Any help would be greatly appreciated.
Below is the program code:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class HeatIndex {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
String token1 = "";
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");
// create List
List<String> temps = new LinkedList<String>();
// while loop
while(inFile1.hasNext()){
// find next line
token1 = inFile1.next();
// initialize temps
temps.add(token1);
}
// close inFile1
inFile1.close();
// create array
String[] tempsArray = temps.toArray(new String[0]);
// for-each loop
for(String s : tempsArray){
// display s to make sure program works correctly
System.out.println(s);
}
}
}
Your program is unable to locate your file. Make sure the file is in your working directory, or change new File("KeyWestTemp.txt") to provide a complete path (e.g. C:/Users/...../KeyWestTemp.txt).
Apparently, the file KeyWestTemp.txt is not found by the Java program. The most likely problem is that you haven't placed it in the right place.
You have 2 options:
Place the file in the working directory, from where you run the java command
When initializing the Scanner, set the full path: new Scanner(new File("/file/path/to/KeyWestTemp.txt")) to the file
Two ways to fix it:
Put your txt file in the same dir of your Java program.
Write the full path of the txt file (c:/files...). Remember to use File.separator instead of the "/" or "\" to make the program platform independent.

Java noob question - how to store a string to a new text file

Here is my scenario:
Selenium grabbed some text on the html page and convert it to a string (String store_txt = selenium.getText("text");) - the text is dynamically generated.
Now I want to store this string into a new text file locally every time I run this test, should I use FileWriter? Or is it as simple as writing a System.out.println("string");?
Do I have to write this as a class or can I write a method instead?
Thanks in advance!!
Use createTempFile to create a new file every time, use FileWriter to write to the file.
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class Main {
public static void main(String[] args) throws IOException {
File f = File.createTempFile("selenium", "txt");
FileWriter writer = new FileWriter(f);
writer.append("text");
}
}
Yes, you need to use a FileWriter to save the text to file.
System.out.println("string");
just prints to the screen in console mode.
Always remember to close the filewriter afterwards using
writer.close()
Otherwise you could end up with a half written file.

Categories