Batch file to compare two different files having different data - file

I want to compare both files, if data is not matched, then print a message "DATA is not the same" and, if they match successfully, print "DATA is the same".
Content of First File (Live.txt):
Last
4000
5000
(2 Row affected)
Content Second File(Sup.txt) :
Last
3000
6000
(2 Row affected)
OS: Windows7

On Microsoft Windows you can use fc command.
On Linux and similar systems
cmp <file1> <file2>
will tell you if the files are different and:
diff <file1> <file2>
will show the differences.

we can also write large files byte by byte with a particular layout and fill the differences in the excel
import java.awt.image.SampleModel;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class FlatFileComparator {
/*
* Get the three flat files.
*
* One for Layout, Second for Expected File Third for Actual file
*/
public static void main(String args[]) throws Exception {
String fileName = "recordLayout.txt";
String actualFileName = "Actual.txt";
String expectedFileName = "Expected.txt";
List<String> recordLayout = null;
FlatFileComparator fb = new FlatFileComparator();
recordLayout = fb.getFileLayout(fileName);
fb.compareExpectedActual(actualFileName, expectedFileName, recordLayout);
}
// Get the Record Names of the Layout and put it in the List with the Field
// Name, Start Index and End Index
public List<String> getFileLayout(String layoutFileName) throws Exception {
List<String> fileLayoutList = new ArrayList<String>();
File layoutFile = new File(layoutFileName);
FileInputStream layoutFileInputStream = new FileInputStream(layoutFile);
BufferedReader layoutBuffReader = new BufferedReader(
new InputStreamReader(layoutFileInputStream));
String currentLine;
try {
while ((currentLine = layoutBuffReader.readLine()) != null) {
if ((currentLine.trim().equals(""))) {
throw new Exception(
"There should not be any empty lines in the middle of the Layout File");
}
String fieldName = currentLine.substring(0,
currentLine.indexOf(":"));
String startIndex = currentLine.substring(
currentLine.indexOf(":") + 2, currentLine.indexOf(","));
String endIndex = currentLine.substring(
currentLine.indexOf(",") + 1,
currentLine.lastIndexOf(")"));
fileLayoutList.add(fieldName);
fileLayoutList.add(startIndex);
fileLayoutList.add(endIndex);
// System.out.println(fieldName);
}
} catch (IOException e) {
// TODO Auto-generated catch block
throw new Exception(
"You have not provided the Layout File for processing. Please provide it and try again");
}
return fileLayoutList;
}
// Get the Actual and Expected File and compare according to the position
public void compareExpectedActual(String actualFileName,
String expectedFileName, List<String> fileLayoutList)
throws Exception {
File actualFile = new File(actualFileName);
File expectedFile = new File(expectedFileName);
FileInputStream actualFileInputStream = new FileInputStream(actualFile);
BufferedReader actBuffReader = new BufferedReader(
new InputStreamReader(actualFileInputStream));
FileInputStream expectedFileInputStream = new FileInputStream(
expectedFile);
BufferedReader expBuffReader = new BufferedReader(
new InputStreamReader(expectedFileInputStream));
HSSFWorkbook excelWorkbook = new HSSFWorkbook();
HSSFSheet excelSheet = excelWorkbook.createSheet("File Comparator");
HSSFRow headerExcelRow = excelSheet.createRow(1);
HSSFRow currExcelRow = null;
HSSFCell headerExcelCell = null;
HSSFCell currExcelCell = null;
headerExcelCell = headerExcelRow.createCell(1);
headerExcelCell.setCellValue("Field Name");
for (int fieldName = 2, listNum = 0; listNum < fileLayoutList.size(); fieldName++) {
currExcelRow = excelSheet.createRow(fieldName);
currExcelCell = currExcelRow.createCell(1);
// System.out.println(listNum);
currExcelCell.setCellValue(fileLayoutList.get(listNum));
listNum += 3;
}
System.out.println(fileLayoutList.size());
int excelNum = 2;
for (String actualFileCurrLine, expectedFileCurrLine; (actualFileCurrLine = actBuffReader
.readLine()) != null
&& (expectedFileCurrLine = expBuffReader.readLine()) != null; excelNum += 4) {
char[] actualArray = actualFileCurrLine.toCharArray();
char[] expectedArray = expectedFileCurrLine.toCharArray();
for (int i = 0, excelRow = 2; i < fileLayoutList.size(); i += 3, excelRow++) {
boolean resultOfCompare = false;
String expectedString = "";
String actualString = "";
for (int j = Integer.parseInt(fileLayoutList.get(i + 1)); j <= Integer
.parseInt(fileLayoutList.get(i + 2)); j++) {
expectedString += expectedArray[j - 1];
// System.out.println("Array Index"+j);
System.out.println(fileLayoutList.get(i + 1));
System.out.println(fileLayoutList.get(i + 2));
actualString += actualArray[j - 1];
}
if (expectedString.equals(actualString))
resultOfCompare = true;
System.out.println(expectedString + "-" + actualString);
System.out.println("Row Number" + excelRow);
headerExcelCell = headerExcelRow.createCell(excelNum);
headerExcelCell.setCellValue("Actual");
headerExcelCell = headerExcelRow.createCell(excelNum + 1);
headerExcelCell.setCellValue("Expected");
headerExcelCell = headerExcelRow.createCell(excelNum + 2);
headerExcelCell.setCellValue("Result");
System.out.println("Cell Value" + "[" + excelRow + ","
+ excelNum + "]=" + actualString);
currExcelRow = excelSheet.getRow(excelRow);
currExcelCell = currExcelRow.createCell(excelNum);
currExcelCell.setCellValue(actualString);
System.out.println("Cell Value" + "[" + excelRow + ","
+ (excelNum + 1) + "]=" + actualString);
currExcelCell = currExcelRow.createCell(excelNum + 1);
currExcelCell.setCellValue(expectedString);
System.out.println("Cell Value" + "[" + excelRow + ","
+ (excelNum + 2) + "]=" + resultOfCompare);
currExcelCell = currExcelRow.createCell(excelNum + 2);
currExcelCell.setCellValue(resultOfCompare);
}
}
FileOutputStream s = new FileOutputStream("FlatfileComparator.xls");
excelWorkbook.write(s);
}
}

Related

How to stop other conditional formatting from disappearing when hackmodding databars into solid fills?

EPPlus has no support for extLst thing which is needed to make databars conditional formatting with solid fill. They are gradient by themselves without modifications.
I coded this to modify worksheet's xml directly (this gets databars from worksheet XML and then adds required extLst nodes):
public static Random Rnd = new Random();
public static string GenerateXlsId()
{
//{29BD882A-B741-482B-9067-72CC5D939236}
string id = string.Empty;
for (int i = 0; i < 32; i++)
if (Rnd.NextDouble() < 0.5)
id += Rnd.Next(0, 10);
else
id += (char)Rnd.Next(65, 91);
id = id.Insert(8, "-");
id = id.Insert(13, "-");
id = id.Insert(18, "-");
id = id.Insert(23, "-");
return id;
}
public static void FixDatabarsAtWorksheet(OfficeOpenXml.ExcelWorksheet eworksheet)
{
System.Xml.XmlNodeList databars = eworksheet.WorksheetXml.GetElementsByTagName("dataBar");
if (databars.Count > 0)
{
string conditional_formattings_str = string.Empty;
for (int i = 0; i < databars.Count; i++)
{
string temp_databar_id = GenerateXlsId();
databars[i].ParentNode.InnerXml += #"<extLst>
<ext uri=""{B025F937-C7B1-47D3-B67F-A62EFF666E3E}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">
<x14:id>{" + temp_databar_id + #"}</x14:id>
</ext>
</extLst>";
//--
string temp_sqref = databars[i].ParentNode.ParentNode.Attributes["sqref"].Value;
string left_type = string.Empty;
string left_val = string.Empty;
string right_type = string.Empty;
string right_val = string.Empty;
string color = string.Empty;
Color databar_fill_color = Color.Empty;
Color databar_border_color = Color.Empty;
for (int j = 0; j < databars[i].ChildNodes.Count; j++)
if (databars[i].ChildNodes[j].LocalName == "cfvo" && databars[i].ChildNodes[j].Attributes["type"] != null)
{
if (string.IsNullOrEmpty(left_type))
left_type = databars[i].ChildNodes[j].Attributes["type"].Value;
else if (string.IsNullOrEmpty(right_type))
right_type = databars[i].ChildNodes[j].Attributes["type"].Value;
if (databars[i].ChildNodes[j].Attributes["val"] != null)
if (string.IsNullOrEmpty(left_val))
left_val = databars[i].ChildNodes[j].Attributes["val"].Value;
else if (string.IsNullOrEmpty(right_val))
right_val = databars[i].ChildNodes[j].Attributes["val"].Value;
}
else if (databars[i].ChildNodes[j].LocalName == "color")
{
color = databars[i].ChildNodes[j].Attributes["rgb"].Value;
int argb = Int32.Parse(color, System.Globalization.NumberStyles.HexNumber);
databar_fill_color = Color.FromArgb(argb);
databar_border_color = Color.FromArgb(255,
databar_fill_color.R - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.R - 50,
databar_fill_color.G - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.G - 50,
databar_fill_color.B - 50 < 0 ? databar_fill_color.R + 50 : databar_fill_color.B - 50);
}
string temp_conditional_formatting_template = #"<x14:conditionalFormatting xmlns:xm=""http://schemas.microsoft.com/office/excel/2006/main"">
<x14:cfRule type=""dataBar"" id=""{" + temp_databar_id + #"}"">
<x14:dataBar minLength=""" + (string.IsNullOrEmpty(left_val) ? "0" : left_val) + "\" maxLength=\"" + (string.IsNullOrEmpty(right_val) ? "100" : right_val) + "\" gradient=\"0\" " + (databar_border_color.IsEmpty ? string.Empty : "border = \"1\"") + ">";
temp_conditional_formatting_template += Environment.NewLine + "<x14:cfvo type=\"" + (left_type.ToLower() == "min" ? "autoMin" : left_type) + "\" />";
temp_conditional_formatting_template += Environment.NewLine + "<x14:cfvo type=\"" + (right_type.ToLower() == "max" ? "autoMax" : right_type) + "\" />";
if (!databar_border_color.IsEmpty)
temp_conditional_formatting_template += Environment.NewLine + "<x14:borderColor rgb=\"" + BitConverter.ToString(new byte[] { databar_border_color.A, databar_border_color.R, databar_border_color.G, databar_border_color.B }).Replace("-", "") + "\" />";
temp_conditional_formatting_template += Environment.NewLine + #"</x14:dataBar>
</x14:cfRule>
<xm:sqref>" + temp_sqref + #"</xm:sqref>
</x14:conditionalFormatting>";
conditional_formattings_str += temp_conditional_formatting_template;
}
databars[0].ParentNode.ParentNode.ParentNode.InnerXml += #"<extLst>
<ext uri=""{78C0D931-6437-407d-A8EE-F0AAD7539E65}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"">
<x14:conditionalFormattings>" + conditional_formattings_str + #"
</x14:conditionalFormattings>
</ext>
</extLst>";
}
}
And this really makes databars solid fill, the problem is any other conditional formatting like GreaterThan loses it's style when true.
For example I add databar and GreaterThan 123 (green) conditional formattings.
Excel still see coditional formatting rule GreaterThan 123, but the style is not set when it's true (green is not set). While databars is displayed correctly at same time.
I don't know where to look... Someone help!
Thats the problem with hacks - they are so fragile! :)
I was able to get it work with another hack - setting the style differential formatting (dxf) reference which seems to be dropped when epplus saves. What might be happening is epplus only thinks there is one dxf on save so it doesnt set the value since excel will assume it is the first dxf style (index 0) but that is a bit of a guess.
Anyway, if you set the dxfid via XML manually it will find it. But order counts here, you have to apply the databar hack last otherwise it will hit the wrong reference:
[TestMethod]
public void FixDatabarsAtWorksheetTest()
{
//https://stackoverflow.com/questions/58417819/how-to-stop-other-conditional-formatting-from-disappearing-when-hackmodding-data
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.AddRange(new[]
{
new DataColumn("Col1", typeof(int)), new DataColumn("Col2", typeof(int)), new DataColumn("Col3", typeof(object))
});
for (var i = 0; i < 10; i++)
{
var row = datatable.NewRow();
row[0] = i;
row[1] = i * 10;
row[2] = Path.GetRandomFileName();
datatable.Rows.Add(row);
}
//Create a test file
var fi = new FileInfo(#"c:\temp\FixDatabarsAtWorksheetTest.xlsx");
if (fi.Exists)
fi.Delete();
using (var pck = new ExcelPackage(fi))
{
var workbook = pck.Workbook;
var doc = workbook.Worksheets.Add("Sheet1");
doc.Cells.LoadFromDataTable(datatable, true);
//Set the greater than
var gtConditional = doc
.ConditionalFormatting
.AddGreaterThan(doc.Cells["A2:A11"]);
gtConditional.Formula = "2";
gtConditional.Style.Fill.BackgroundColor.Color = Color.GreenYellow;
//Fix the gt
var xdoc = doc.WorksheetXml;
var nsm = new XmlNamespaceManager(xdoc.NameTable);
nsm.AddNamespace("default", xdoc.DocumentElement.NamespaceURI);
var gtNode = xdoc.SelectSingleNode("/default:worksheet/default:conditionalFormatting[#sqref=\"A2:A11\"]", nsm);
//Create the new attribute for table
var att = xdoc.CreateAttribute("dxfId");
att.Value = "0";
gtNode
.FirstChild
.Attributes.Append(att);
//Set the bar condition LAST
var barConditional = doc
.ConditionalFormatting
.AddDatabar(doc.Cells["B2:B11"], Color.FromArgb(99, 195, 132));
barConditional.HighValue.Type = eExcelConditionalFormattingValueObjectType.Num;
barConditional.LowValue.Type = eExcelConditionalFormattingValueObjectType.Num;
barConditional.HighValue.Value = 82;
barConditional.LowValue.Value = 0;
FixDatabarsAtWorksheet(doc);
pck.Save();
}
}
I get this:
Not sure how feasible this is for you depending on how many conditional formats you have but its worth a shot.

Reading text files into array

I'm trying to store girl and boy names into an array.
I got most of the code except the storing the files into an array.
This is what girls.txt looks like
Emma 125125
Elaina 415545
Kim 545454
Boys.txt:
Devan 45645
Tom 4545
Chris 4879797
i need help storing the names and numbers from files into array boynames array and girlnames array. I show where i need help with comments in code
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Project1Names {
public static void main(String[] args) {
Scanner inputStream = null;
String[][] boynames = new String[1000][2];
String[][] girlnames = new String[1000][2];
String line = null;
boolean isFoundB = false;
boolean isFoundG = false;
try {
inputStream = new Scanner(new FileInputStream("boys.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening file boys.txt");
System.exit(0);
}
Scanner inputStreamGirls = null;
try {
inputStreamGirls = new Scanner(new FileInputStream("girls.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening file girls.txt");
System.exit(0);
}
int count = 0;
while (count < 1000){
inputStream = boynames[count][0]; //Error here
inputStream = boynames[count][1]; //here
count++;
}
count = 0;
while (count < 1000 ){
inputStreamGirls = girlnames[count][0]; //here
inputStreamGirls = girlnames[count][1]; //here
count++;
}
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the first name that you would like to find the popularity of.\n Be sure to capitalize the first letter of the name.\n");
String answer = keyboard.next();
count = 0;
while(count < 1000){
if (boynames[count][0] == answer){
System.out.println(boynames[count][0] + " is ranked " + count + " among boys with " + boynames[count][1] + " namings");
isFoundB = true;
}
if (girlnames[count][0] == answer){
System.out.println(girlnames[count][0] + " is ranked " + count + " among girls with " + girlnames[count][1] + " namings");
isFoundG = true;
}
count++;
}
if(isFoundB == false){
System.out.println(answer + " is not ranked among the top 1000 boy names.");
}
if(isFoundG == false){
System.out.println(answer + " is not ranked among the top 1000 girl names.");
}
inputStreamGirls.close();
inputStream.close();
keyboard.close();
}
}
You will need to call the scanner methods to actually read from the input file.
scanner.next() reads one string token from the input.
So instead of this part:
inputStream = boynames[count][0]; //Error here
inputStream = boynames[count][1]; //here
You would do:
boynames[count][0] = inputStream.next();
boynames[count][1] = inputStream.next();

javamail also extract attachments of encapsulated message Content-Type: message/rfc822

I want to extract ALL the attachments of an .eml message which is encapsulated (Content-Type: message/rfc822) in the message InputStream
InputStream is = new FileInputStream(Path);
MimeMessage mime = new MimeMessage(null, is);
private String getAttachments(p) throws
MessagingException, IOException {
if ( p.isMimeType("multipart/*")) {
Multipart multiPart = (Multipart) p.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
String disp = part.getDisposition();
if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT) {
file_name = part.getFileName();
part.saveFile(Attachments_Folder + "\\" + MailFileName + "_" + file_name);
}
}
}
}
is.close()
Also, when the Content-Type is message/rfc822, the part.getFileName() is null and therefore the saved file has no extension and I don't know how to get this one.
MIME does not require every body part to have a file name. If the part doesn't have a file name and you need one, you'll have to make one up yourself.
Note also that you want to be very careful when using a file name that you get in an email message. It could be something unexpected or malicious, e.g., containing "../../../../../whatever".
I did it by adding a new filename to the included message as an .eml file and a recursion with the included message
import java.util.*;
import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.*;
import java.io.FileInputStream.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.Part;
import javax.mail.Multipart;
getAttachments(Path) ;
//function
private String getAttachments(path) throws
MessagingException, IOException {
InputStream is = new FileInputStream(path);
MimeMessage p = new MimeMessage(null, is);
if ( p.isMimeType("multipart/*")) {
// if (contentType.contains("multipart")) {
Multipart multiPart = (Multipart) p.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart)multiPart.getBodyPart(partCount);
String disp = part.getDisposition();
if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
file_name = part.contentType == "message/rfc822" ? "message_inclus" + partCount + ".eml" : MimeUtility.decodeText(part.getFileName());
exportedpath = Attachments_Folder + "/" + MailFileName + "_" + file_name;
part.saveFile(exportedpath);
if ( part.contentType == "message/rfc822" ) {
getAttachments(exportedpath)
}
}
}
}
is.close()
return 1
}
Better use org.apache.commons.mail.util.MimeMessageParser.
MimeMessageParser has as method called hasAttachments() which
returns true , if message has an attachments.
Then loop through the all attachments and check for content-type
message/rfc822 from getContentType().
Create new MimeMessage with the DataSource InputStream
final MimeMessage message = new MimeMessage(null,attachment.getInputStream());
Finally you have MimeMessage.
Maven Dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>RELEASE</version>
</dependency>
Code Sample:
public void readEmails() throws Exception{
// mail server connection parameters
String host = "host";
String user = "username";
String pwd = "pwd";
// connect to my pop3 inbox
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("pop3");
store.connect(host, user, pwd);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
// get the list of inbox messages
Message[] messages = inbox.getMessages();
if (messages.length == 0) System.out.println("No messages found.");
for (int i = 0; i < messages.length; i++) {
// stop after listing ten messages
if (i > 10) {
System.exit(0);
inbox.close(true);
store.close();
}
final MimeMessageParser mimeMessageParser = new MimeMessageParser((MimeMessage) messages[i]);
mimeMessageParser.parse();
if (mimeMessageParser.hasAttachments()) {
List<DataSource> attachmentList = mimeMessageParser.getAttachmentList();
System.out.println("Number of attachments: " +attachmentList.size());
for (DataSource attachment:attachmentList
) {
System.out.println("Name: "+attachment.getName()+" Content Type: "+attachment.getContentType());
if (attachment.getContentType().equals("message/rfc822")) {
final MimeMessage message = new MimeMessage(null,attachment.getInputStream());
System.out.println("Subject of the attached failure Mail:" + message.getSubject());
}
}
}
System.out.println("Message " + (i + 1));
System.out.println("From : " + messages[i].getFrom()[0]);
System.out.println("Subject : " + messages[i].getSubject());
System.out.println("Sent Date : " + messages[i].getSentDate());
System.out.println();
}
inbox.close(true);
store.close();
}

the given path formate is not supported in C# windows application while uploading files to ftp

i want to upload files to ftp but i get an error
The given path's format is not supported.
i have mention my code below kindly help me.
the path giving error , what should i need to keep path like ?
the following is my path
this.path = #"ftp://ip address/Requests/";
public bool UploadDocsToFTP(string SourceFilePath, string FileName)
{
string ServerUri = "";
string FTPUserName = "";
string FTPPassword = "";
string ftpURI = "";
try
{
try
{
ServerUri = ConfigurationManager.AppSettings["LinuxFileServerUri"];
FTPUserName = ConfigurationManager.AppSettings["LinuxFtpUserName"];
FTPPassword = ConfigurationManager.AppSettings["LinuxFtpPassword"];
string[] splitfilename = SourceFilePath.Split('\\');
//String businesRegId = splitfilename[2];
//String userRegId = splitfilename[3];
//String folderType = splitfilename[3];
//ftpURI = "ftp://" + ServerUri + "//" + businesRegId + "//" + userRegId;
//if (!string.IsNullOrEmpty(folderType))
// ftpURI += "//" + folderType;
//ServerUri = "ftp://" + ServerUri + "//" + businesRegId + "//" + userRegId + "//";
//if (!string.IsNullOrEmpty(folderType))
// ServerUri += folderType + "//";
// SetMethodRequiresCWD();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ip address/Requests" + FileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
FileStream fs = File.OpenRead(SourceFilePath + FileName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = request.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (WebException e)
{
String status = ((FtpWebResponse)e.Response).StatusDescription;
if (UploadDocsToFTP_DirNotExists(SourceFilePath, FileName))
{
return true;
}
return false;
}
}
catch (Exception ex)
{
ex.ToString();
return false;
}
return true;
}
A URL (which is what your path is) cannot contain spaces or other certain characters, so you have to encode it.
You can use System.Net.WebUtility for this.
// instead of this:
// FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ip address/Requests" + FileName);
// do this:
string path = System.Net.WebUtility.UrlEncode("ftp://ip address/Requests" + FileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);

Loop, iterate with unexpected results, Propertie

package javaapplication43;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import java.io.FileInputStream;
public class JavaApplication43 {
int totalResults = 45; //
int itemsperPage = 10;
int i = 0;
int j = 0;
int count = 0;
FileOutputStream output = null;
Properties prop = new Properties();
FileInputStream input=null;
public JavaApplication43() throws FileNotFoundException, IOException {
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("totalResults", "45");
prop.setProperty("itemsperPage", "10");
prop.setProperty("?", "?");
// save properties to project root folder
prop.store(output, null);
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("totalResults"));
System.out.println(prop.getProperty("itemsperPage"));
System.out.println(prop.getProperty("?"));
}
public void makeLoop() {
for (i = 1; i <= (totalResults / itemsperPage) + 1; i++) {
System.out.println("nextPage " + i);
for (; j < i * itemsperPage; j++) {
if (j > totalResults) {
break;
}
System.out.println("Filenumber " + (j + 1));
}
}
}
public static void main(String[] args) throws IOException {
JavaApplication43 myTest = new JavaApplication43();
myTest.makeLoop();
}
}
*This Code gives the Result:
nextPage1: Filnumber1, Filnumber2...Filenumber10
nextPage2: Filenumber11, Filenumber12.., Filenumber20
nextPage5: Filenumber41, Filenumber42.., Filenumber46
And so on. I expect the result so, if i start the next time with a sheduller it should start
with the nextpage2 and print the files from 11-20,
if i start again the programm it should start with the nextpage 3 and print the files from 21-30 and so on depends on the value wich i have for totalResults.
The Solution is may to save the value in the Property to make it Persistent, so that
if i run the Programm again, it will read the Property config.properties to start on the right index, but i dont know how to iterate, through the loop. ?
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import java.io.FileInputStream;
public class JavaApplication43_with_Main_3 {
public static void main(String[] args) throws IOException {
int totalResults = 45; //
int itemsperPage = 10;
int i = 0;
int j = 0;
FileOutputStream output = null;
Properties prop = new Properties();
FileInputStream input = null;
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println("nextPage Prop " + prop.getProperty("nextPage"));
String nextPage = prop.getProperty("nextPage");
int intNextPage = Integer.parseInt(nextPage);
System.out.println("intNextPage " + intNextPage);
for (i = intNextPage; i <= (totalResults / itemsperPage) + 1; i++) {
int jNextPage=intNextPage-1;
System.out.println("nextPage here " + i);
for (j=jNextPage*itemsperPage; j < i * itemsperPage; j++) {
// System.out.println("j ist "+j);
if (j > totalResults) {
break;
}
System.out.println("Filenumber " + (j + 1));
}
String strI = "" + (i + 1);
System.out.println("hello " + strI);
output = new FileOutputStream("config.properties");
prop.setProperty("nextPage", strI);
prop.store(output, null);
break;
}
}
}
This is the does make loop and printing out
nextPage 1, Filenumber1,Filenumber2,..,Filenumber10
then it saves the nextPage value into the Property File.
If you start again, it does printing out
nextPage 2, Filenumber11,Filenumber12,...,Filenumber20
You should have e Propertiy File with the Name, config.properties
and but the key nextPage and the value 1, nextPage=1;--->config.properties

Resources