I am trying to retrieve the full file path from the classes that have been edited. I can retrieve the comments, version number, author and date but can't seem to get the full file path that has been edited when more than one class has been included into the project.
I use these to retrieve the Comments and Author:
String comments = pc.getPendingChanges().getComment();
System.out.println("Comments: " + comments);
String author = pc.getPendingChanges().getAllPendingChanges()[0].getPendingSetOwnerDisplay();
System.out.println("Author: " + author);
I use this to retrieve the path:
String fileName = pc.getPendingChanges().getAllPendingChanges()[0].getLocalItem();
System.out.println("FileName: " + fileName);
but I only get this output:
FileName: C:\VS2013\Plugin\PluginTest\HelloWorld.classpath
I need to display the full path with the class name eg
FileName: C:\VS2013\Plugin\PluginTest\HelloWorld.Test.java
Full method displayed below:
#Override
public PolicyFailure[] evaluate(PolicyContext context)
throws PolicyEvaluationCancelledException {
final PendingCheckin pc = getPendingCheckin();
final List<PolicyFailure> failures = new ArrayList<PolicyFailure>();
final WorkItemCheckinInfo[] AssociatedWorkItems = pc.getWorkItems().getCheckedWorkItems();
WorkItem AssociatedCodeReview = null;
String failureReason = "";
for (int i=0; i<AssociatedWorkItems.length; i++) {
AssociatedCodeReview = AssociatedWorkItems[i].getWorkItem();
if (AssociatedCodeReview.getType().getName() == "Code Review") {
break;
}
}
if (AssociatedCodeReview != null) {
if (AssociatedCodeReview.getFields().getField("System.State").getValue()
.toString().equals("Not Approved")) {
failureReason = "Code Review Work Item associated but that is not approved by expert";
failures.add(new PolicyFailure(failureReason, this));
}
} else {
String fileName = pc.getPendingChanges().getAllPendingChanges()[0].getLocalItem();
System.out.println("FileName: " + fileName);
String fileName2 = pc.getPendingChanges().getAllPendingChanges()[0].getServerItem();
System.out.println("FileName2: " + fileName2);
String[] fileName3 = pc.getPendingChanges().getAffectedTeamProjectPaths();
System.out.println("FileName3: " + fileName3[0]);
//System.out.println("Found " + pc.getPendingChanges().getAffectedTeamProjectPaths()[0] + " work items.");
String comments = pc.getPendingChanges().getComment();
System.out.println("Comments: " + comments);
String author = pc.getPendingChanges().getAllPendingChanges()[0].getPendingSetOwnerDisplay();
System.out.println("Author: " + author);
String version = String.valueOf(pc.getPendingChanges().getAllPendingChanges()[0].getVersion());
System.out.println("Version: " + version);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println("Date Time: " + dateFormat.format(date));
}
return failures.toArray(new PolicyFailure[failures.size()]);
}
It actually does work, it was an error with my Eclipse install.
String fileName = pc.getPendingChanges().getAllPendingChanges()[x].getLocalItem();
Related
Connection conn = SqlConnection.getConnection("jdbc:mysql://localhost:3306/stocks");
Statement statement = conn.createStatement();
File path = new File("/Users/Zack/Desktop/JavaDB/BALANCESHEETS");
for(File file: path.listFiles()) {
if (file.isFile()) {
String fileName = file.getName();
String ticker = fileName.split("\\_")[0];
if (ticker.equals("ASB") || ticker.equals("FRC")) {
if (ticker.equals("ASB")) {
ticker = ticker + "PRD";
}
if (ticker.equals("FRC")) {
ticker = ticker + "PRD";
}
}
//CSVReader reader = new CSVReader(new FileReader(file));
//List entries = reader.readAll();
//ArrayList<String> entry = new ArrayList<String>();
Reader reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}
String string = builder.toString();
ArrayList<String> stringResult = new ArrayList<String>();
if (string != null) {
String[] splitData = string.split("\\s*,\\s*|\\n");
for (int i = 0; i <splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() ==0)) {
stringResult.add(splitData[i].trim());
}
}
}
String columnName = null;
int yearCount = 0;
for (int i = 0; i < stringResult.size(); i++) {
int sL = stringResult.get(i).length();
for (int x = 0; x < sL; x++) {
if (Character.isLetter(stringResult.get(i).charAt(x))) {
yearCount = 0;
System.out.println("index: " + i);
columnName = stringResult.get(i);
columnName = columnName.replace(" ", "_");
System.out.println(columnName);
i++;
break;
}
}
yearCount++;
String value = stringResult.get(i);
System.out.println("Year: " + stringResult.get(yearCount) + " Value: " + value + " Stock: " + ticker + " Column: " + columnName );
if (!(columnName == null)) {
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUE ('" + ticker + "','" + stringResult.get(yearCount) + "','" + value + "')";
String writeValues2 = "UPDATE BalanceSheet "
+ "SET ticker = '" + ticker + "', "
+ "Year = '" + stringResult.get(yearCount) + "', "
+ columnName + " = '" + value + "' "
+ "WHERE ticker = '" + ticker + "'";
statement.executeUpdate(writeValues2);
}
}
Towards the bottom of the code are two queries I tried, I'm trying to get all data organized by ticker and year into a table, "writeColumns" works but it's making a new row for every new "value" put into "columnName". My second attempt "writeColumns2" doesn't do anything.
I want to update the same row with a certain year for all values and then move onto the next year, then next ticker.
If I have understood your question correctly, you want to insert a row if it doesn't exists but update the values if it already does. You need to use ON DUPLICATE KEY UPDATE
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUES (?,?,?) "
+"ON DUPLICATE KEY UPDATE " + columnName +"=?";
Statement statement = conn.prepareStatement(writeValues);
statement.setString(1,ticker);
statement.setString(2,stringResult.get(yearCount));
statement.setString(3, value);
This will solve your immidiate problem provided you create a UNIQUE index on ticker,year
However there are lot's of other issues here.
An update for each column - Currently you are doing an insert/update for each column on the table. What you are supposed to do is to insert update all the columns at one.
You are not using prepared statements addressed in my code sample
You shouldn't be doing this at all the best way to batch process data is to use MYSQL's built in LOAD DATA INFILE command. If your data is not in a format that can be easily imported into mysql, what your Java code can do is to transform it into a format that can be. Such a code will be a lot simpler and neater than what you have now
I was trying to move file using move file method .but getting this error
"java.io.IOException: Failed to delete original file"
this is my code.
this is for file move without error
public void moveWithoutError(String fileName){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String ts = dateFormat.format(date);
File source = new File("D:/Inbound/");
File dest = new File("D:/Archive/");
for (File file : source.listFiles()) {
String x = (source + "/" + file.getName());
String y = (dest + "/" + addTimestamp(file.getName(), ts));
if(file.getName().equals(fileName)){
File sourceFile = new File(x);
File destnFile = new File(y);
try{
FileUtils.moveFile(sourceFile, destnFile);
System.out.println("Moved file:"+y);
}catch(Exception e){
System.out.println("Unable to move file:"+y);
System.out.println(e);
e.printStackTrace();
}
break;
}
}
}
This code is written for moving the file with containing error
public void moveWithError(String fileName){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String ts = dateFormat.format(date);
File source = new File("D:/Inbound\\");
File dest = new File("D:\\Error\\"); /
for (File file : source.listFiles()) {
String x = (source + "/" + file.getName());
String y = (dest + "/" + addTimestamp(file.getName(), ts));
if(file.getName().equals(fileName)){
File f1 = new File(x);
if(f1.renameTo(new File(y))){
System.out.println(" moved: " + y);
} else {
System.out.println("unable to move: " + y);
}
break;
}
}
}
This code is used to add timestamp to moved file
public static String addTimestamp(String name, String ts) {
int lastIndexOf = name.lastIndexOf('.');
return (lastIndexOf == -1 ?
name + "_" + ts
:
name.substring(0, lastIndexOf) + "-" + ts +
name.substring(lastIndexOf))
.replaceAll("[\\/:\\*\\?\"<>| ]", "");
}
}
while executing this code exception come
abd exception is
"java.io.IOException: Failed to delete original file 'D:\Inbound\Testdata.xlsx' after copy to 'D:\Archive\Testdata-20140812121814.xlsx'"
Note - this file is nor open neither accessing by other process
Please help :(
Exception
java.io.IOException: Failed to delete original file 'D:\Inbound\Testdata.xlsx' after copy to 'D:\Archive\Testdata-20140812130655.xlsx'
at org.apache.commons.io.FileUtils.moveFile(FileUtils.java:2664)
at CRP.MoveFile.moveWithoutError (MoveFile.java:77)
at CRP.CRPDAO.callMoveFile (CRPDAO.java:562)
at CRP.CRP_FileDependency.main (CRP_FileDependency.java:163)
I have a linux java program that is reading and writing to a CIFS mounted Windows file share. See code snippet at bottom.
After execution, there are files named "cifs*" left in the directory. If the target directory is on the local file system, the code works like a champ. However, if the target directory is a CIFS mounted Windows file share, I get the left-over files. I'm not sure what configuration changes I need to make to fix. Any help is greatly appreciated.
FileRenameMutex myFileRenameMutex = new FileRenameMutex("/WindowsMount/MoveLock");
class FileRenameMutex
{
// global variables
String lockFileBasename;
String unusedExtension = "_Unused";
String unusedFilename;
String inUseFilename;
String localMachineAddress;
String formattedTime;
// log4j logger for this class
public static Logger logMutex = Logger.getLogger(FileRenameMutex.class.getName());
public FileRenameMutex(String _lockFileBase) {
this.lockFileBasename = _lockFileBase;
logMutex.debug("FileRenameMutex: Constructor, with file " + lockFileBasename + " user = " + System.getProperty("user.name"));
try {
localMachineAddress = InetAddress.getLocalHost().getHostAddress();
//localMachineAddress = InetAddress.getLocalHost().getHostName();
} catch ( Exception e ) {
localMachineAddress = "UNKNOWN_HOST";
logMutex.error(" Could not determine host address. " + e.getMessage());
}
// set the file names
unusedFilename = lockFileBasename + unusedExtension;
inUseFilename = lockFileBasename + "_" + localMachineAddress;
logMutex.debug(" Local machine = " + localMachineAddress);
logMutex.debug(" Unused file name = " + this.unusedFilename);
logMutex.debug(" In Use file name = " + this.inUseFilename);
}
public boolean tryAcquire() throws InterruptedException {
boolean returnVal = false;
File unusedFile = new File(unusedFilename);
File inUseFile = new File(inUseFilename);
formattedTime = new Date().toString();
String inUseText = "This file created by the Alfresco cron job to MoveFileAndCreateDir "
+ "(move files from Unfiled to Filed folders).\n"
+ "Running on " + localMachineAddress + "\n Started at " + formattedTime + "\n";
try {
FileWriter fstream = new FileWriter(inUseFile);
BufferedWriter out = new BufferedWriter(fstream);
// attempt to rename file
logMutex.debug(" Attempting to rename mutex file " + unusedFilename + " to " + inUseFilename);
if ( unusedFile.renameTo(inUseFile) ) {
logMutex.debug(" Rename to inUse successful");
out.write(inUseText);
out.flush();
out.close();
returnVal = true; // lock was acquired
} else {
// System.out.println("Rename to inUse failed");
logMutex.error(" Rename of " + unusedFilename + " to " + inUseFilename + " failed in tryAcquire().");
}
} catch ( Exception e ) {
throw new InterruptedException("Error acquiring lock in tryAcquire(): " + e.getMessage());
}
return returnVal;
}
public void release() {
File unusedFile = new File(unusedFilename);
File inUseFile = new File(inUseFilename);
String unusedText = "This file was last by the Alfresco cron job to MoveFileAndCreateDir "
+ "Ran on " + localMachineAddress + "\n Started at " + formattedTime + "\n";
try {
FileWriter fstream = new FileWriter(inUseFile);
BufferedWriter out = new BufferedWriter(fstream);
out.write(unusedText);
out.flush();
out.close();
// attempt to rename file
logMutex.debug(" Attempting to rename active mutex file " + inUseFilename + " back to " + unusedFilename);
if ( inUseFile.renameTo(unusedFile) ) {
logMutex.debug(" Rename back to unused successful");
} else {
logMutex.error(" Rename of " + inUseFilename + " to " + unusedFilename + " failed in release().");
}
} catch ( Exception e ) {
logMutex.error("Error resetting lock file in release(): " + e.getMessage());
}
} // release()
} // end of class FileRenameMutex
How can I split a flat string based on 0102**? string tokenizer is working for only **. Is there any way to split based on 0102**? Please suggest
Here is my complete method
private String handleCibil(InterfaceRequestVO ifmReqDto, String szExtIntType) throws MalformedURLException, org.apache.axis.AxisFault, RemoteException {
/* Declaration and initiliazation */
ConfVO confvo = ifmReqDto.getExtConfVo();
String szResponse = null;
String cibilResponse = null;
String errorResponse = null;
String endpointURL = null;
long timeOut = confvo.getBurMgr().getBurInfo(szExtIntType).getTimeOut();
endpointURL = formWebServiceURL(confvo, szExtIntType);
URL url = new URL(endpointURL);
log.debug("Input xml for cibil "+ifmReqDto.getIfmReqXML());
BasicHttpStub stub= new BasicHttpStub(url,new org.apache.axis.client.Service());
szResponse = stub.executeXMLString(ifmReqDto.getIfmReqXML());
//szResponse=szResponse.replaceAll("&", "&");
log.debug("szResponse "+szResponse);
/* Validate if the obtained response is as expected by IFM */
try {
extDao = new ExtInterfaceXMLTransDAO(ifmReqDto.getSemCallNo(), ifmReqDto.getIdService());
extDao.updateRqstRespXML10g(ifmReqDto.getInterfaceReqNum(), szResponse, GGIConstants.IFM_RESPONSE);
//log.debug("CIBIL_RESPONSE_XPATH " + GGIConstants.CIBIL_RESPONSE_XPATH);
Document xmlDocument = DocumentHelper.parseText(szResponse);
String xPath = GGIConstants.RESPONSE_XPATH;
List<Node> nodes = xmlDocument.selectNodes(xPath);
for (Node node : nodes) {
String keyValue = node.valueOf(GGIConstants.RESPONSE_XPATH_KEY);
// log.debug("keyValue : " + keyValue);
if (keyValue.equalsIgnoreCase(GGIConstants.RESPONSE_XPATH_KEY_VALUE)) {
// log.debug("node value : " + node.getText());
cibilResponse = node.getText();
}
}
log.debug("cibilResponse " + cibilResponse);
String errorResponseXPATH = GGIConstants.CIBIL_ERROR_RESPONSE_XPATH;
List<Node> errorResponseNode = xmlDocument.selectNodes(errorResponseXPATH);
for (Node node : errorResponseNode) {
errorResponse = node.getText();
}
log.debug("errorResponse " + errorResponse);
if(cibilResponse!=null && cibilResponse.length()>0)
{
StringTokenizer cibilResponseResults = new StringTokenizer(cibilResponse,"**");
String tempResponse="";
ArrayList probableMatchList = new ArrayList();
while (cibilResponseResults.hasMoreElements()) {
tempResponse = (String) cibilResponseResults.nextElement();
if(tempResponse.length()>=80)
{
String memberRefNo = tempResponse.substring(69, 80).replaceAll(" ", "");
log.debug("memberRefNo " + memberRefNo);
if (memberRefNo.length() > 0) {
if (Integer.parseInt(memberRefNo) > 0) {
cibilResponse = tempResponse;
cibilResponse = cibilResponse+"**";
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
cibilResponse = tempResponse+"**";
}
}
log.debug("After finding the Member reference number cibilResponse " + cibilResponse);
log.debug("After finding the Probable reference list " + probableMatchList);
// TKN 008
cibilResponse=StringEscapeUtils.unescapeXml(cibilResponse).replaceAll("[^\\x20-\\x7e]","");
ifmReqDto.setIfmTransformedResult(cibilResponse);
ifmReqDto.setProbableMatchList(probableMatchList);
}
if (errorResponse!=null && errorResponse.length()>0) {
throw new GenericInterfaceException(errorResponse
+ " for the seq_request " + ifmReqDto.getSeqRequest() + " Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.CIBIL_ERROR_CODE);
}
else if (cibilResponse==null || StringUtils.isEmpty(cibilResponse) ) {
throw new GenericInterfaceException("Cibil TUEF response is empty >> cibil Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.INTERFACE_ERROR_RESPONSE);
}
/* Setting Instinct response to ifmReqDto object */
} catch (SQLException e) {
log.error("SQLException while connecting to DataBase. Exception message is ", e);
throw new GenericInterfaceException("SQLException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.DB_OPERATION_ERROR);
} catch (GenericInterfaceException exp) {
log.error("Exception occured while valid:", exp);
throw exp;
} catch (Exception exp) {
log.error("Exception occured while valid:", exp);
throw new GenericInterfaceException("GeneralException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.UNKNOWN_ERROR);
}
return szResponse;
}
I recommend checking out the Java documentation, it provides a really good reference to start with. The .split method uses a regex to split up a string based on a delimiter.
String[] tokens = myString.split("0102\\*\\*");
For now I suspect that you forgot to escape * in split regex.
Try maybe
String[] resutl = yourString.split("0102\\*\\*");
In case you want * to represent any character then use . instead of *
String[] resutl = yourString.split("0102..");
In case you want * to represent any digit use \\d instead
String[] resutl = yourString.split("0102\\d\\d");
String string = "blabla0102**dada";
String[] parts = string.split("0102\\*\\*");
String part1 = parts[0]; // blabla
String part2 = parts[1]; // dada
Here we have a String: "blabla0102**dada", we call it string. Every String object has a method split(), using this we can split a string on anything we desire.
Do you mean literally split by "0102**"? Couldn't you use regex for that?
String[] tokens = "My text 0102** hello!".split("0102\\*\\*");
System.out.println(tokens[0]);
System.out.println(tokens[1]);
Basics of this program;
Runs a webcrawler based on PerentUrl and Keyword specified by the user in Controller (main). If the Keyword is found in the page text, the Url is then saved to an array list;
ArrayList UrlHits = new ArrayList();
Once the crawl is complete the program will call methods from the WriteFile class in the main to write a html file containing all the UrlHits.
WriteFile f = new WriteFile();
f.openfile(Search);
f.StartHtml();
f.addUrl(UrlHits);
f.EndHtml();
f.closeFile();
All but f.addUrl work correctly, creating a html file with the correct name and directory. But none of the strings from the ArrayList output to the file.
public static void main(String[] args) throws Exception {
RobotstxtConfig robotstxtConfig2 = new RobotstxtConfig();
String crawlStorageFolder = "/Users/Jake/Documents/sem 2/FYP/Crawler/TestData";
int numberOfCrawlers = 1;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
config.setMaxDepthOfCrawling(21);
config.setMaxPagesToFetch(24);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
Scanner perentUrl = new Scanner(System.in);
System.out.println("Enter full perant Url... example. http://www.domain.co.uk/");
String Url = perentUrl.nextLine();
Scanner keyword = new Scanner(System.in);
System.out.println("Enter search term... example. Pies");
String Search = keyword.nextLine();
System.out.println("Searching domain :" + Url);
System.out.println("Keyword:" + Search);
ArrayList<String> DomainsToInv = new ArrayList<String>();
ArrayList<String> SearchTerms = new ArrayList<String>();
ArrayList<String> UrlHits = new ArrayList<String>();
DomainsToInv.add(Url);
SearchTerms.add(Search);
controller.addSeed(Url);
controller.setCustomData(DomainsToInv);
controller.setCustomData(SearchTerms);
controller.start(Crawler.class, numberOfCrawlers);
WriteFile f = new WriteFile();
f.openfile(Search);
f.StartHtml();
f.addUrl(UrlHits);
f.EndHtml();
f.closeFile();
}
}
public class Crawler extends WebCrawler {
#Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String domain = page.getWebURL().getDomain();
String path = page.getWebURL().getPath();
String subDomain = page.getWebURL().getSubDomain();
String parentUrl = page.getWebURL().getParentUrl();
String anchor = page.getWebURL().getAnchor();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Domain: '" + domain + "'");
System.out.println("Sub-domain: '" + subDomain + "'");
System.out.println("Path: '" + path + "'");
System.out.println("Parent page: " + parentUrl);
System.out.println("Anchor text: " + anchor);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
Header[] responseHeaders = page.getFetchResponseHeaders();
if (responseHeaders != null) {
System.out.println("Response headers:");
for (Header header : responseHeaders) {
System.out.println("\t" + header.getName() + ": " + header.getValue());
}
}
System.out.println("=============");
ArrayList<String> SearchTerms = (ArrayList<String>) this.getMyController().getCustomData();
ArrayList<String> UrlHits = (ArrayList<String>) this.getMyController().getCustomData();
for (String Keyword : SearchTerms) {
System.out.println("Searching Keyword: " + Keyword);
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
int KeywordCounter = 0;
String pagetext = htmlParseData.getText();
Pattern pattern = Pattern.compile(Keyword);
Matcher match1 = pattern.matcher(pagetext);
if (match1.find()) {
while (match1.find()) {
KeywordCounter++;
}
System.out.println("FOUND " + Keyword + " in page text. KeywordCount: " + KeywordCounter);
UrlHits.add(url);
for (int i = 0; i < UrlHits.size(); i++) {
System.out.print(UrlHits.get(i) + "\n");
System.out.println("=============");
}
} else {
System.out.println("Keyword search was unsuccesful");
System.out.println("=============");
}
}
}
}
public class WriteFile {
private Formatter x;
public void openfile(String keyword) {
try {
x = new Formatter(keyword + ".html");
} catch (Exception e) {
System.out.println("ERROR");
}
}
public void StartHtml() {
x.format("%s %n %s %n %s %n %s %n %s %n ", "<html>", "<head>", "</head>", "<body>", "<center>");
}
public void addUrl(ArrayList<String> UrlHits) {
for (String list : UrlHits) {
x.format("%s%s%s%s%s%n%s%n", "", list, "", "<br>");
}
}
public void EndHtml() {
x.format("%s %n %s %n %s %n", "</center>", "</body>", "</html>");
}
public void closeFile() {
x.close();
}
}
Apologies for the class headers outside the code blocks its a little fiddly. I have tried a few different "for" statements to get the method to output the array list but it doesn't seem to be having it. The strings are being added to the array list as i can call them using a for loop in the main. But when i pass the array list to the method addUrl, it comes up with squat. is there an easier way to use arraylists using formatters and .format?
Thanks for you help