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();
}
}
Related
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;
}
I have a txt file "HighScoreList.txt" in my project.
The Problem is that there must be characters on that file, but when I open it in Eclipse, its empty. Removing it from eclipse and opening it with notepad removes all characters from that file.
My method writes on that file.
public void registerHighScore(Player p) {
int score = p.getScore();
String name = p.getName();
{
currentHighScores.add("X. "+name+" - "+score); //place doesnt matter as the actual place gets determined in formatHList
formatHList();
}
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter(HighScoreManager.class.getResource("/highscore/HighScoreList.txt").getPath()));//persistancy
for (String s : currentHighScores) {
writer.write(s);
writer.newLine();
writer.flush();
}
writer.close();
} catch (IOException e) {
return;
}
}
I have checked that there must be characters in the textfile because
public ArrayList<String> getCurrentHighScores() {
ArrayList<String> result = new ArrayList<String>();
try {
BufferedReader bufferedReader = new BufferedReader(
new FileReader(HighScoreManager.class.getResource("/highscore/HighScoreList.txt").getPath()));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.add(line);
}
bufferedReader.close();
return result;
} catch (IOException e) {
}
return null;
}
The ArrayList createt with that method actually contains Strings in the X. Name - Score format.
Need help from you regarding a Scenario, i.e., I have to take a value from DB like "42258258.2300" and convert this into "42,258,258.00" value.
And again need to check whether this value present in downloaded CSV file.
I used below code for read from CSV file but am not getting the output. Kindly help me on this.
String strFile = "outputfile.csv";
FileInputStream fstream = new FileInputStream(strFile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String ss = "$42,699,561.00";
if(strLine.contains(ss)){
System.out.println ("Success"); }
}
in.close();
What do you get if you print strLine? Are you really getting the string?
This code works for me
public void getFileInformation(){
String strFile = "/Users/myUser/Documents/outputfile.csv";
BufferedReader br = null;
String strLine = "";
String ss = "$42,699,561.00";
try {
br = new BufferedReader(new FileReader(strFile));
while ((strLine= br.readLine()) != null) {
if(strLine.contains(ss)){
System.out.println ("Success");
}else{
System.out.println (strLine);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
But the content "$42,699,561.00"; should really exist in the file
I have an xml abc.xml
<soapenv:Envelope>
<soapenv:Header/>
<soapenv:Body>
<mes:SomeRq>
<RqID>?</RqID>
<MsgRqHdr>
....
</mes:SomeRq>
</soapenv:Body>
</soapenv:Envelope>
Is there a way i can search mes:, from this xml and replace it with ins:
Thanks in advance.
public static void findreplcae(String strFilePath) throws IOException {
String currentString = "mes:";
String changedString = "ins:";
BufferedReader reader = new BufferedReader(new FileReader(strFilePath));
StringBuffer currentLine = new StringBuffer();
String currentLineIn;
while ((currentLineIn = reader.readLine()) != null) {
System.out.println(currentLineIn);
boolean bool = false;
String trimmedLine = currentLineIn.trim();
System.out.println(trimmedLine);
if (trimmedLine.contains(currentString)) {
trimmedLine.replace(currentString, changedString);
bool = true;
if (bool != true) {
currentLine = currentLine.append(currentLineIn + System.getProperty("line.separator"));
}
}
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(strFilePath));
writer.write(currentLine.toString());
writer.close();
}
}
It's not good idea to parse it as a text file. DocumentBuilder.parse to parse the file, call getDocumentElement() and check for getPrefix. If it matches, replace with setPrefix(). Note you have to register prefix if not yet done already.
Check this page for tutorial.
Some issues:
trimmedLine.replace(currentString, changedString);, the result is returned, so you have to store it somewhere. See here
What is this supposed to do?
bool = true;
if (bool != true) {
currentLine = currentLine.append(currentLineIn + System.getProperty("line.separator"));
}
Don't close the reader while reading in a loop.
If you want to overwrite the original file, this should do (although I am not sure, if you really want to trim the lines):
String currentString = "mes:";
String changedString = "ins:";
try {
BufferedReader reader = new BufferedReader(new FileReader(strFilePath));
StringBuffer newContents = new StringBuffer();
String currentLineIn = null;
while ((currentLineIn = reader.readLine()) != null) {
String trimmedLine = currentLineIn.trim();
if (trimmedLine.contains(currentString)) {
newContents.append(trimmedLine.replace(currentString, changedString));
}
else {
newContents.append(trimmedLine);
}
newContents.append(System.getProperty("line.separator"));
}
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(strFilePath));
writer.write(newContents.toString());
writer.close();
} catch (IOException e) {
// TODO handle it
}
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;
}