How to extract starting of a String in Java - java

I have a text file with more than 20,000 lines and i need to extract specific line from it. The output of this program is completely blank file.
There are 20,000 lines in the txt file and this ISDN line keeps on repeating lots of time each with different value. My text file contains following data.
RecordType=0(MOC)
sequenceNumber=456456456
callingIMSI=73454353911
callingIMEI=85346344
callingNumber
AddInd=H45345'1
NumPlan=H34634'2
ISDN=94634564366 // Need to extract this "ISDN" line only
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
String line = "";
String line2 = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
while ((line = reader.readLine()) != null) {
// extract logic starts here
if (line.startsWith("ISDN") == true) {
System.out.println("hello");
returnValue += line + "\n";
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnValue;
}

We will assume that you use Java 7, since this is 2014.
Here is a method which will return a List<String> where each element is an ISDN:
private static final Pattern ISDN = Pattern.compile("ISDN=(.*)");
// ...
public List<String> getISDNsFromFile(final String fileName)
throws IOException
{
final Path path = Paths.get(fileName);
final List<String> ret = new ArrayList<>();
Matcher m;
String line;
try (
final BufferedReader reader
= Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
m = ISDN.matcher(line);
if (m.matches())
ret.add(m.group(1));
}
}
return ret;
}

Related

How to fetch a string from a output in console in java and compare it with the expected value

Below is the code:
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The following is my output:
Context successfully set
Script started
LXKADMIN|In/OutBoundValidation|-|50149.11065.26960.11788|inbound=OFF|outbound=OFF
inbound=OFF|outbound=OFF
Script complete
STEP 1: COMPLETED
PASSED: step1
I want to fetch the line 5 "inbound=OFF|outbound=OFF" and check if its value is matching "inbound=OFF|outbound=OFF" then my test case will pass else it will fail.
The TCL Script is:
tcl;
eval {
puts "Script started"
set schemaValidationStr [mql temp query bus LXKADMIN In/OutBoundValidation * select id description dump '|']
puts $schemaValidationStr
set schemaValidation [string range $schemaValidationStr 57 end]
puts $schemaValidation
puts "Script complete"
}
Any suggestion will be really helpful.
If your question is just how to verify that the output returned by your TCL script, contains a specific line, than you might try this:
public static final int CHECK_LINE_NR = 4;
public static final String EXPECTED_LINE_VALUE = "inbound=OFF|outbound=OFF";
public boolean verifyScriptOutput(ChannelExec channel)
throws IOException
{
// Check all lines in output
BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
String line;
int linenr = 0;
while ((line = reader.readLine()) != null)
{
linenr++;
if (linenr == CHECK_LINE_NR)
return (line.equals(EXPECTED_LINE_VALUE));
}
// If we get here, output has less lines
return (false);
} // verifyScriptOutput
The point at which you are reasoning is not possible because you can not access the console and see what is visualized. Instead you should process the input that the console gets, and outputs it, which is the line variable in your case.
If for you is enough to see that inbound=OFF|outbound=OFF you can search that substring in the line like this:
if(line.indexOf("inbound=OFF|outbound=OFF") != -1) {
// you have a match
}
I'm not sure I understood the question, but you might try this:
public static final int CHECK_LINE_NR = 4;
public static final String CHECK_LINE_VALUE = "inbound=OFF|outbound=OFF";
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int linenr;
boolean line_check_passed;
linenr = 0;
line_check_passed = false;
while ((line = reader.readLine()) != null) {
linenr++;
if (linenr == CHECK_LINE_NR)
line_check_passed = line.equals(CHECK_LINE_VALUE);
System.out.println(line);
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public static boolean check(InputStream in, int line, String expected) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int i = 0;
String str;
while ((str = reader.readLine()) != null) {
if (i < line)
i++;
else
return expected.equals(str);
}
return false;
}

Creating folder from text

I am getting
newDir D:\template_export\template\attachments\processed\enumeration\blocker.gif\enumeration\critical.gif\enumeration\high.gif\enumeration\low.gif\enumeration\major.gif\enumeration\medium.gif\enumeration\minor.gif\enumeration\normal.gif\enumeration\unassigned.gif\enumeration\unassigned2.gif\workflow\close.gif\workflow\defer.gif\workflow\duplicate.gif\workflow\inprogress.gif\workflow\new.gif\workflow\open.gif\workflow\reject.gif\workflow\remind.gif\workflow\reopen.gif\workflow\resolve.gif\workflow\unconfigure.gif\workflow\unresolve.gif\workflow\verify.gif\workflow\wontdo.gif\workflow\works.gif\workitemtype\bug.gif\workitemtype\enhancement.gif\workitemtype\general.gif\workitemtype\task.gif\workitemtype
new directory false
reached
java.nio.file.NoSuchFileException: D:\template_export\template\attachments\1.gif -> D:\template_export\template\attachments\processed\enumeration\blocker.gif\enumeration\critical.gif\enumeration\high.gif\enumeration\low.gif\enumeration\major.gif\enumeration\medium.gif\enumeration\minor.gif\enumeration\normal.gif\enumeration\unassigned.gif\enumeration\unassigned2.gif\workflow\close.gif\workflow\defer.gif\workflow\duplicate.gif\workflow\inprogress.gif\workflow\new.gif\workflow\open.gif\workflow\reject.gif\workflow\remind.gif\workflow\reopen.gif\workflow\resolve.gif\workflow\unconfigure.gif\workflow\unresolve.gif\workflow\verify.gif\workflow\wontdo.gif\workflow\works.gif\workitemtype\bug.gif\workitemtype\enhancement.gif\workitemtype\general.gif\workitemtype\task.gif\workitemtype\unknown.gifprocess_template_license.htmltemplate.messagestemplate_en_US.messages
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileCopy.move(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.move(Unknown Source)
at java.nio.file.Files.move(Unknown Source)
at Test.main(Test.java:60)
Error.
My code is :
public class Test {
public static void main(String[] args) {
File orgDirectory = new File("D://template_export/template/attachments"); // replace this filename
// with the path to the folder
// that contains the original images
String fileContent = "";
try (BufferedReader br = new BufferedReader(new FileReader(new File(orgDirectory, "attachments.txt")))) {
for (String line;
(line = br.readLine()) != null;) {
fileContent += line;
}
} catch (Exception e) {
e.printStackTrace();
}
String[] newLocations = fileContent.split(",");
File[] orgFiles = orgDirectory.listFiles(new FileFilter() {#Override
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".gif");
}
});
File destinationFolder = new File("D://template_export/template/attachments/processed");
if (!destinationFolder.exists()) {
System.out.println("here" + destinationFolder.mkdir());
}
int max = Math.min(orgFiles.length, newLocations.length);
for (int i = 0; i < max; i++) {
String newLocation = newLocations[i];
int lastIndex = newLocation.lastIndexOf("/");
if (lastIndex == -1) {
continue;
}
String newDirName = newLocation.substring(0, lastIndex);
System.out.println("newDirName " + newDirName);
String newName = newLocation.substring(lastIndex);
System.out.println("newName " + newName);
File newDir = new File(destinationFolder, newDirName);
System.out.println("newDir " + newDir);
if (!newDir.exists()) {
System.out.println("new directory " + newDir.mkdir());
}
try {
System.out.println("reached");
Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You're concatenating all the lines of the attachments.txt file into a single destination string. Judging from the exception message, it appears that the attachments file does not contain commas at the end of each line. Thus you end up with a destination consisting of a single file name, seemingly in a deeply nested directory.
Instead, I suggest that you read the lines in one at a time into an ArrayList<String>, rather than concatenating and later splitting the destinations.
ArrayList<String> newLocations = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(new File(orgDirectory, "attachments.txt")))) {
for (String line; (line = br.readLine()) != null;) {
newLocations.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Then you can use newLocations.size() where you now use newLocations.length and use newLocations.get(i) where you use newLocations[i].
EDIT: As #griFlo points out in a comment, a simpler alternative to reading the file into a list of lines is:
List<String> newLocations = Files.readAllLines(Paths.get("attachments.txt"));
If the file will not read properly with UTF-8 decoding (which is what the above call will use), or if you're compiling with Java 7, you'll have to use the two-argument version of readAllLines():
List<String> newLocations = Files.readAllLines(Paths.get("attachments.txt"),
StandardCharsets.US_ASCII); // or whatever encoding is appropriate

How to pass parameter to data provider in testng from csv file

Am reading data from csv file , i have test for which this data will be the input .
i want it to run as tescase for every set of value. for that am using data provider
The problem is , it is taking only the last set row of data , please help me in debugging the code
For eg : if my csv has following data
name1 id1 text1
name2 id2 text2
name3 id3 text3
it taking only last row name3 id3 text3 and running the test only once not three times.
#DataProvider(name = "test")
public Object[][] provider( ) throws InterruptedException
{
Object[][] returnObject ;
String[] checkpoint = ReadfromCSV();
count = count + 1;
returnObject = new Object[][]{checkpoint };
return returnObject;
}
#Test(description = "Test", groups = "test" , dataProvider = "test")
public void compare(String val1,String val2,String val3,String val4,String val5,String val6,String val7,String val8,String val9,String val10,String val11 ) {
System.out.println("1:" + val1);
System.out.println("4:" + val2);
System.out.println("5:" + val3);
}
#SuppressWarnings("null")
public String[] ReadfromCSV() throws InterruptedException {
String[] data= null;
String csvFile = "F:/sample1.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(cvsSplitBy);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return data;
}
You should read entire file in data provider and return iterator of test cases. Here is some pseudocode for data provider. Notice that I used List<String []> to store test cases instead of Object[][]. This allows you do define test cases dynamically.
#DataProvider(name = "test")
public Iterator<Object []> provider( ) throws InterruptedException
{
List<Object []> testCases = new ArrayList<>();
String[] data= null;
//this loop is pseudo code
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(cvsSplitBy);
testCases.add(data);
}
return testCases.iterator();
}
public String[][] ReadfromCSV() throws InterruptedException {
int count =0;
String[] data= null;
String returnObj[][] = null;
//System.out.println(System.getProperty("user.dir"));
String csvFile = System.getProperty("user.dir")+ "/src/test/resources/testdata.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<String> content = new ArrayList<String>();
try {
//this loop is pseudo code
br = new BufferedReader(new FileReader(csvFile));
int datalength = 0;
int listsize =0;;
while ((line = br.readLine()) != null) {
// use comma as separator
content.add(line);
}
System.out.println(content);
listsize = content.size();
datalength = content.get(0).split(cvsSplitBy).length;
returnObj = new String[listsize][datalength];
for (int i = 0; i<listsize; i++) {
data = content.get(i).split(cvsSplitBy);
for (int j=0; j< datalength ; j++) {
returnObj[i][j] = data[j];
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return returnObj;
}}

Java read certain line from txt file

I want to read the 2nd line of text from a file and have that put into an array. I already have it working on the first line.
[ Code removed as requested ]
The while loop above shows how I read and save the 1st line of the text file into an array. I wish to repeat this process from the 2nd line only into a different array.
File Content:
Sofa,Armchair,Computer Desk,Coffee Table,TV Stand,Cushion,Bed,Mattress,Duvet,Pillow
599.99,229.99,129.99,40.00,37.00,08.00,145.00,299.99,24.99,09.99
Just get rid of the first readLine() call, and move the String.split() call into the loop.
Simply use the BufferedReader class to read the entire file and then manipulate the String output.
Something along these lines
public static String readFile(String fileName) throws IOException {
String toReturn = "";
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
toReturn = toReturn+"\n"+sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return toReturn;
}
would yield a String which can then be easily used.
public static void main(String[] args)
{
String filePath = args[0];
String[] lineElements = getLine(filePath,2).split(",");
}
public static String getLine(String path,int line)
{
List<String> cases = new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader(path));
String currLine = "";
while((currLine = br.readLine()) != null){
cases.add(currLine);
}
}catch(IOException ex){
ex.printStackTrace();
}
return cases.get(line - 1);//2nd line
}

find specific string after certain pattern in a txt file

so i am new to java.please offer some sample codes if possible.
The situation is i have a html format in a text file. i need to read the file and find the string after a pattern which is 'data-name'. i need to find every string after the "data-name" through the entire text file. i did some research online . i already used html parser to get the html and store it in a text file. i know i might need to use regular expression. so please help me. Thank you guys!
below is my code for getting the html. the result is concatenated.
public static void main(String[] args) {
try {
URL url = new URL("https://twitter.com/search?q=%23JENOSMROOKIESOPENFOLBACK&src=tren");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
PrintWriter out = new PrintWriter(new FileWriter("C:/Users/Desktop/htmlsourcecode.txt"));
while ((line = in.readLine()) != null) {
System.out.println(line);
out.print(line);
}
out.close();
}
How about something like this
// External resource(s).
BufferedReader in = null;
PrintWriter out = null;
try {
URL url = new URL(
"https://twitter.com/search?q=%23JENOSMROOKIESOPENFOLBACK&src=tren");
// read text returned by server
in = new BufferedReader(new InputStreamReader(
url.openStream()));
String line;
// out = new PrintWriter(new FileWriter(
// "htmlsourcecode.txt"));
final String DATA_NAME = "data-name=\"";
while ((line = in.readLine()) != null) {
int pos1 = line.indexOf(DATA_NAME); // opening position.
if (pos1 > -1) { // did we match?
// Add the length of the string.
pos1 += DATA_NAME.length();
// find the closing quote.
int pos2 = line.indexOf("\"", pos1 + 1);
if (pos2 > -1) {
String dataName = line.substring(pos1,
pos2);
System.out.println(dataName);
// out.print(line);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close external resource(s).
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
out.close();
}
}

Categories

Resources