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
Related
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class JavaClass {
public static void main(String[] args) {
// Things start here
int[][] multi = new int[5][10];
for(int p = 1; p < 5; p++)
{
for(int h = 1;h < 10;h++)
{
System.out.println("Enter the score for Player " + String.valueOf(p) + ", Hole " + String.valueOf(h) + " :");
String v = stringReader();
multi[p][h] = Integer.parseInt(v);
System.out.println(String.valueOf(v));
}
}
}
public static String stringReader()
{
String value;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
value = bufferedReader.readLine();
} catch (IOException e) {
value = "0";
}
return value;
}
Hello! I am currently working on a project for my Grade 12 Computer Science course where i am asked to make a "Golf Score Tracker" the description of the project is (add to the code below code that calculates and displays each golfers individual score)
I've tried working with while loops however whatever I do it does not seem to display. My teacher is also stuck lol he is actually the reason I am here asking for help on this project
I've searched for hours and tried everything to fix this code. I've been working with the example below and after updating appropriate variables this works fine through till the end of processing the first email. It seems to pause indefinitely. I had to alter code at (//check if the content is an inline image) as variables appear to need declaration before they were used but have not changed anything apart from that. Any help before I loose my mind will be much appreciated.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Original code at https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
My code below... (output below that)
package com.mail.coder;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
public class FetchingEmail2 {
public static void fetch(String pop3Host, String storeType, String user,
String password) {
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.store.protocol", "pop3");
properties.put("mail.pop3.host", pop3Host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
// emailSession.setDebug(true);
// create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect("mail.DOMAIN.com", "USERNAME#DOMAIN.com", "PASS");
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
writePart(message);
String line = reader.readLine();
if ("YES".equals(line)) {
message.writeTo(System.out);
} else if ("QUIT".equals(line)) {
break;
}
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username =
"abc#gmail.com";// change accordingly
String password = "*****";// change accordingly
//Call method fetch
fetch(host, mailStoreType, username, password);
}
/*
* This method checks for content-type
* based on which, it processes and
* fetches the content of the message
*/
public static void writePart(Part p) throws Exception {
if (p instanceof Message)
//Call method writeEnvelope
writeEnvelope((Message) p);
System.out.println("----------------------------");
System.out.println("CONTENT-TYPE: " + p.getContentType());
//check if the content is plain text
if (p.isMimeType("text/plain")) {
System.out.println("This is plain text");
System.out.println("---------------------------");
System.out.println((String) p.getContent());
}
//check if the content has attachment
else if (p.isMimeType("multipart/*")) {
System.out.println("This is a Multipart");
System.out.println("---------------------------");
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
writePart(mp.getBodyPart(i));
}
//check if the content is a nested message
else if (p.isMimeType("message/rfc822")) {
System.out.println("This is a Nested Message");
System.out.println("---------------------------");
writePart((Part) p.getContent());
}
//check if the content is an inline image
else if (p.isMimeType("image/jpeg")) {
System.out.println("--------> image/jpeg");
Object o = p.getContent();
InputStream x = (InputStream) o;
// Construct the required byte array
System.out.println("x.length = " + x.available());
**int i;
byte[] bArray = new byte[x.available()];**
while ((i = (int) ((InputStream) x).available()) > 0) {
int result = (int) (((InputStream) x).read(bArray));
if (result == -1)
i = 0;
break;
}
FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg");
f2.write(bArray);
}
else if (p.getContentType().contains("image/")) {
System.out.println("content type" + p.getContentType());
File f = new File("image" + new Date().getTime() + ".jpg");
DataOutputStream output = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
com.sun.mail.util.BASE64DecoderStream test =
(com.sun.mail.util.BASE64DecoderStream) p
.getContent();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = test.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
else {
Object o = p.getContent();
if (o instanceof String) {
System.out.println("This is a string");
System.out.println("---------------------------");
System.out.println((String) o);
}
else if (o instanceof InputStream) {
System.out.println("This is just an input stream");
System.out.println("---------------------------");
InputStream is = (InputStream) o;
is = (InputStream) o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
}
else {
System.out.println("This is an unknown type");
System.out.println("---------------------------");
System.out.println(o.toString());
}
}
}
/*
* This method would print FROM,TO and SUBJECT of the message
*/
public static void writeEnvelope(Message m) throws Exception {
System.out.println("This is the message envelope");
System.out.println("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("FROM: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("TO: " + a[j].toString());
}
// SUBJECT
if (m.getSubject() != null)
System.out.println("SUBJECT: " + m.getSubject());
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Output
messages.length---5
---------------------------------
This is the message envelope
---------------------------
FROM: Jack Frost <sender#gmail.com>
TO: recipient#domain.com
SUBJECT: another email
----------------------------
CONTENT-TYPE: multipart/alternative; boundary="000000000000096c73056991868c"
This is a Multipart
---------------------------
----------------------------
CONTENT-TYPE: text/plain; charset="UTF-8"
This is plain text
---------------------------
testing
----------------------------
CONTENT-TYPE: text/html; charset="UTF-8"
This is a string
---------------------------
<div dir="ltr">testing</div>
I have drawn multiple ellipses using a loop as shown below, and the results are perfect using one color for all the ellipses, but my target is to color each ellipse with different color. Is there any way to let the property Color.BLUE change its value in each iteration?
for (int i = 0; i < 3; i++)
{
XYShapeAnnotation unitCircle1 = new XYShapeAnnotation(
new Ellipse2D.Double((FinalArayOfOptpar[s][i] - Math.abs(FinalArayOfOptpar[s][i + 2])),
(FinalArayOfOptpar[s][i + 1] - Math.abs(FinalArayOfOptpar[s][i + 3])),
Math.abs(FinalArayOfOptpar[s][i + 2] * 2.0), Math.abs(FinalArayOfOptpar[s][i + 3] * 2.0)),
new BasicStroke(0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10.2f), Color.BLUE);
xyPlot.addAnnotation(unitCircle1);
}
tens of XYShapeAnnotations will be created…so creating multiple instances of XYShapeAnnotation will not work for my purpose.
Happily, an instance XYShapeAnnotation is small—just 48 bytes each in the example below. You'll want to profile to be sure.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.geom.Ellipse2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYShapeAnnotation;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
* #see https://stackoverflow.com/a/35236100/230513
*/
public class AnnotationTest {
private static final BasicStroke stroke = new BasicStroke(2.0f);
private static final int N = 16;
private static final int S = 8;
public static void main(String[] args) {
EventQueue.invokeLater(new AnnotationTest()::display);
}
private void display() {
XYDataset data = createDataset();
JFreeChart chart = ChartFactory.createXYLineChart("ArcTest", "X", "Y",
data, PlotOrientation.VERTICAL, true, true, false);
XYPlot plot = chart.getXYPlot();
XYLineAndShapeRenderer renderer
= (XYLineAndShapeRenderer) plot.getRenderer();
renderer.setBaseShapesVisible(true);
for (int i = 0; i < N; i++) {
double x = data.getXValue(0, i) - S / 2;
double y = data.getYValue(0, i) - S / 2;
Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, S, S);
Color color = Color.getHSBColor((float) i / N, 1, 1);
renderer.addAnnotation(new XYShapeAnnotation(ellipse, stroke, color));
}
ChartFrame frame = new ChartFrame("Test", chart);
frame.pack();
frame.setVisible(true);
}
private static XYDataset createDataset() {
XYSeriesCollection result = new XYSeriesCollection();
XYSeries series = new XYSeries("ArcTest");
for (int i = 0; i < N; i++) {
series.add(i * S, i * S);
}
result.addSeries(series);
return result;
}
}
I have the code. Some of names are in Polish, but I think it's not a problem.
In this code I create randomly filled array, write it to the .txt file and then create another array using data read from this file. Unfortunately in static method hasNextDouble() method return false and my array is filled with 0.0's. Why is that so? If I open this .txt file via notepad it contains doubles that can be read. Where is a problem?
package algorytmyz1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Random;
import java.util.Scanner;
class Tablica {
private int w;
private int k;
private double[][] tab;
//konstruktor
public Tablica(int w,int k) {
this.w = w;
this.k = k;
tab = new double[w][k];
Wypelnij();
Zapisz();
}
//wypelnia macierz liczbami od 0 do 9
private void Wypelnij(){
Random rand = new Random();
for(int i=0; i<w; i++)
for(int j=0; j<k; j++)
//generuje pseudolosowe liczby rzeczywiste między 0 a 10
tab[i][j]=rand.nextDouble() * 10;
}
private void Zapisz() {
try (PrintWriter fout = new PrintWriter("macierz1.txt"))
{
fout.println("Macierz:");
fout.println(w);
fout.println(k);
for (int i=0; i<w; i++)
{
for (int j=0; j<k; j++)
{
fout.print(tab[i][j] + " ");
}
fout.println();
}
}
catch (IOException e) {
System.out.println("Błąd wejścia/wyjścia.");
}
}
}
public class AlgorytmyZ1 {
public static void main(String[] args) throws FileNotFoundException {
int w,k;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//wprowadzenie liczby wierszy i kolumn macierzy
try {
System.out.println("Podaj liczbę wierszy:");
w = Integer.parseInt(br.readLine());
System.out.println("Podaj liczbę kolumn:");
k = Integer.parseInt(br.readLine());
Tablica macierz = new Tablica(w,k);
}
catch (IOException e) {
System.out.println(e);
}
WczytajWyswietl();
}
public static void WczytajWyswietl() throws FileNotFoundException {
int w, k;
String naglowek;
double[][] tablica;
File file = new File("macierz1.txt");
Scanner fin = new Scanner(file);
naglowek = fin.nextLine();
w = Integer.parseInt(fin.nextLine());
k = Integer.parseInt(fin.nextLine());
tablica = new double[w][k];
while (fin.hasNextDouble())
{
for (int i=0; i<w; i++)
{
for (int j=0; j<k; j++)
tablica[i][j] = fin.nextDouble();
}
}
System.out.println(naglowek);
System.out.println("Liczba wierszy: " + w);
System.out.println("Liczba kolumn: " + k);
for (int i = 0; i<w; i++)
{
for (int j=0; j<k; j++)
{
System.out.print(tablica[i][j] + " ");
}
System.out.println();
}
}
}
The correct answer was that I had to use useLocale(Locale.English) method on my scanner object. I don't know which Locale was set before, but with english everything runs smooth.
I post this answer to my own post because maybe it will be helpful for someone in the future.
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);
}
}