I have this error when I Run the code but no when I Compile it.
Exception in thread "main" java.lang.NullPointerException
at java.util.StringTokenizer.<init>(StringTokenizer.java:199)
at java.util.StringTokenizer.<init>(StringTokenizer.java:221)
at WillinsLaMarkusFileInputOutput.main(WillinsLaMarkusFileInputOutput.java:23)
Here is my complete code
import java.io.*;
public class WillinsLaMarkusFileInputOutput {
public static void main(String[] args) throws IOException {
/* open the files */
// Scanner sc = new Scanner(System.in);
BufferedReader r = new BufferedReader(new FileReader("input.txt"));
BufferedWriter w = new BufferedWriter(new FileWriter("output.txt"));
float[] values = new float[10];
String str = r.readLine();
int i = 0;
float sum = 0.0f, avg = 0.0f;
/* tokenize the string into floats separated by spaces */
java.util.StringTokenizer tk = new java.util.StringTokenizer(str, " ");
while (tk.hasMoreElements()) {
values[i] = Float.valueOf(tk.nextToken()).floatValue();
/* compute sum */
sum += values[i];
i++;
}
/* calculate average */
avg = sum / 10.0f;
/* write results to output.txt */
w.write("Sum: " + sum);
w.newLine();
w.write("Average: " + avg);
w.flush();
/* close the files */
r.close();
w.close();
}
}
Any suggestions on how to fix this ?
The exception goes from this line:
java.util.StringTokenizer tk = new java.util.StringTokenizer(str, " ");
So first let's read the documentation when this constructor may throw NullPointerException:
public StringTokenizer(String str, String delim)
Throws:
NullPointerException - if str is null
Fine. It means that str is null. The str is assigned in this line:
String str = r.readLine();
Now you should read the documentation when r.readLine() may return null:
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So it signals that end of file is reached. As it's the very first attempt to read something from this file it seems that you are reading an empty file.
In general careful documentation reading may greatly help to understand why your program doesn't work.
Related
I'm trying send a set of query results in an email using SSIS. Below is the screen shot and steps for the flow.
Screenshot:
Steps:
1. Using SQL task to get the results of the query in "queryresult" object variable
2. Using the "queryresult" object variable in the Foreach loop and getting the column Values in the string variables "ProjectRefID" and "Accountnumber"
3.Using script task inside the foreachloop container to capture the data in the object variable "query result"
Below is the code inside the script task which I copied from the internet.
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
endregion
namespace ST_77e6b4ea18824b909adc5568475fcf5c
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
Variables varCollection = null;
string header = string.Empty;
string message = string.Empty;
Dts.VariableDispenser.LockForWrite("User::ValidationEmailMessage");
Dts.VariableDispenser.LockForRead("User::Accountnumber");
Dts.VariableDispenser.LockForRead("User::ProjectRefID");
Dts.VariableDispenser.GetVariables(ref varCollection);
if (varCollection["User::ValidationEmailMessage"].Value == string.Empty)
{
header = "Below are the list of Invalid ProjecRefID and Accountnumbers that are not matching with our existing data:\n\n";
header += string.Format("{0}\t{1}\t\t\t{2}\n", "ProjectRefID", "Accountnumber");
varCollection["User::ValidationEmailMessage"].Value = header;
varCollection.Unlock();
}
//Format the query result with tab delimiters
message = string.Format("{0}\t{1}\t{2}",
varCollection["User::ProjectRefID"].Value,
varCollection["User::Accountnumber"].Value);
varCollection["User::ValidationEmailMessage"].Value = varCollection["User::ValidationEmailMessage"].Value + message;
varCollection.Unlock();
Dts.TaskResult = (int)ScriptResults.Success;
}
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
}
}
I tried to resolve this error but somehow I'm not able to figure this out. Let me know if anyone knows how to resolve it.
Unless you require the locking functionality for some reason, you should be able to write the Main method simply as this:
public void Main()
{
string header = string.Empty;
string message = string.Empty;
if (Dts.Variables["User::ValidationEmailMessage"].Value == string.Empty)
{
header = "Below are the list of Invalid ProjecRefID and Accountnumbers that are not matching with our existing data:\n\n";
header += string.Format("{0}\t{1}\t\t\t{2}\n", "ProjectRefID", "Accountnumber");
Dts.Variables["User::ValidationEmailMessage"].Value = header;
}
//Format the query result with tab delimiters
message =
string.Format("{0}\t{1}\t{2}",
Dts.Variables["User::ProjectRefID"].Value,
Dts.Variables["User::Accountnumber"].Value);
Dts.Variables["User::ValidationEmailMessage"].Value = Dts.Variables["User::ValidationEmailMessage"].Value + message;
Dts.TaskResult = (int)ScriptResults.Success;
}
Also, with your string.Format code, you are specifying three indexes, {0}, {1} and {2}, yet you are only providing 2 arguments, i.e. , "ProjectRefID", "Accountnumber");.
Hi i am using [box][1]
[1]: https://www.box.com/ to store my csv file. Size of file is 2GB. Now i want to process each record of file and do some operation based on file content.
what i did:
public class BoxConnector {
public static void main(String[] args) throws IOException {
BoxAPIConnection api = new BoxAPIConnection("My access token");
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
for (BoxItem.Info itemInfo : rootFolder) {
System.out.format("[%s] %s\n", itemInfo.getID(), itemInfo.getName());
BoxFile file = new BoxFile(api, itemInfo.getID());
BoxFile.Info info = file.getInfo();
try {
System.out.println(info.getSize());
File tmpFile = File.createTempFile("file", "temp");
FileOutputStream fsTmpStrem = new FileOutputStream(tmpFile);
long blockSize = 1000;
long roundChunks = info.getSize() / blockSize;
long startByteRange = 0;
long endByteRange = blockSize;
for (long start = 0; start < roundChunks; start++) {
file.downloadRange(fsTmpStrem, startByteRange, endByteRange);
processFile(tmpFile);
startByteRange = endByteRange;
endByteRange = endByteRange + blockSize;
}
//last download block
file.downloadRange(fsTmpStrem, blockSize * roundChunks, info.getSize());
processFile(tmpFile);
} finally {
}
}
}
private static void processFile(File tmpFile) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(tmpFile)));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Process line record");
}
br.close();
//after each process lets delete the temp file
tmpFile.delete();
}
}
with this i am able to get the file name which i have uploaded to box.com. Now i want to read each record and process.
However i need an API which allows me file chunk access .
with this files are getting downloaded as per chunk defined by start and end byte range flag.however due to chunk download i am getting few records broken . Meaning i am not getting complete line say below is my record
16F11C78-D004-4600-8D28-445C087D2A7D
31C99F3D-D4C7-418A-9ACC-D9A382BCD53A
30C1AA92-B5B7-4ABF-A631-A8C150D90C4F
D9FC1DBF-B309-4BB1-8955-D9F48F643E97
i am getting
16F11C78-D004-4600-8D28-445C087D2A7D
31C99F3D-D4C7-418A-9ACC-D9A382BCD53A
30C1AA92-B5B7-4ABF-A631-A8C150D90C4F
D9FC1DBF-
i.e. B309-4BB1-8955-D9F48F643E97 part from last line is missing.
How should i manage this with download API?
This is not currently possible with the Box API. You can only download an entire file.
In a java service, without a function declaration, a function call is there and only compile time error comes. But the output is as expected with no run time errors. How is that possible? Can anyone please explain?
"The method functionName() is undefined" is the error it shows.
Below is the code.
public static final void documentToStringVals(IData pipeline)
throws ServiceException {
// pipeline
IDataCursor pipelineCursor = pipeline.getCursor();
String success = "false";
IData inputDoc = null;
String outputValue = "";
String headerYN = "N";
boolean headerValue = false;
String delimiter = ",";
String newline = System.getProperty("line.separator");
if (pipelineCursor.first("inputDocument") ) {
inputDoc = (IData) pipelineCursor.getValue();
}
else {
throw new ServiceException("inputDocument is a required parameter");
}
if (pipelineCursor.first("delimiter") ) {
delimiter = (String) pipelineCursor.getValue();
}
if (pipelineCursor.first("headerYN") ) {
headerYN = (String) pipelineCursor.getValue();
}
if (headerYN.equalsIgnoreCase("Y")) {
headerValue = true;
}
try {
outputValue = docValuesToString(inputDoc, headerValue, delimiter);
outputValue += newline;
success = "true";
}
catch (Exception e) {
System.out.println("Exception in getting string from document: " + e.getMessage());
pipelineCursor.insertAfter("errorMessage", e.getMessage());
}
pipelineCursor.insertAfter("success", success);
pipelineCursor.insertAfter("outputValue", outputValue);
pipelineCursor.destroy();
}
The code you posted has no reference to "functionName", so I suspect there's a reference to it either in the shared code section or in another Java service in the same folder. Given that all Java services in a folder get compiled into a single class, and therefore all those services need to be compiled together, this could cause the error message when you're compiling the service above.
I am working with csv file having very large dataset. while reading file i had extracted 4th place(BALANCE) ';' separated numeric value from each rows through while loop iteration. and make a list of Double after some mathematical calculation(here incremented).
now I want to store this list of Double in reverse order(from end to beginning).as its original position(here 4th place).example
public static void main(String[] args) throws IOException {
String filename = "abc.csv";
List<Double> list = new ArrayList<Double>();
File file = new File(filename);
Scanner inputStream = new Scanner(file);
inputStream.next();
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(";");
double BALANCE = Double.parseDouble(values[1]);
BALANCE = BALANCE + 1;
ListIterator li = list.listIterator(list.size());
while (li.hasPrevious()) {
values[1] = String.valueOf(li.previous()); }
inputStream.close();
}
} }
You can use Collections.reverse. Example Collections.reverse(list);
I'm using this to send a htlm file direclty to printer and it says invalid flavour which means that the printer does not support the formats. Any one have an idea to do this..
/**
* #param args
*/
public static void main(String[] args) {
// Input the file
FileInputStream textStream = null;
try {
textStream = new FileInputStream("./some.html");
} catch (FileNotFoundException ffne) {
}
if (textStream == null) {
return;
}
// Set the document type
DocFlavor myFormat = DocFlavor.INPUT_STREAM.TEXT_HTML_HOST;
// Create a Doc
Doc myDoc = new SimpleDoc(textStream, myFormat , null);
// Build a set of attributes
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
//aset.add(MediaSize.NA.LEGAL);
aset.add(Sides.ONE_SIDED);
// discover the printers that can print the format according to the
// instructions in the attribute set
PrintService services = PrintServiceLookup.lookupDefaultPrintService();
//PrintServiceLookup.lookupPrintServices(myFormat, aset);
// Create a print job from one of the print services
//System.out.println("====5======="+service.get);
//if (services.length > 0) {
for (int i = 0; i < services.getSupportedDocFlavors().length; i++) {
System.out.println("====getSupportedDocFlavors======="+services.getSupportedDocFlavors()[i]);
}
DocPrintJob job = services.createPrintJob();
try {
job.print(myDoc, aset);
} catch (PrintException pe) {
System.out.println("====PrintException======="+pe);
}
//}
}
It says
sun.print.PrintJobFlavorException: invalid flavor
You are trying to force printer to handle (render) HTML document onto the paper. It will never work that way. And ofcourse the flavor you are sending is not supported.
First of all you need to render HTML into some graphical representation and then send it to printer. There are no good cross-platform tools for Java that could render modern HTML pages. But there is one in JavaFX and i guess you could use it to handle the task.
About printing the final image you can read here:
http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html
or see the code here:
http://www.java2s.com/Code/Java/2D-Graphics-GUI/PrintanImagetoprintdirectly.htm
or just find any other resource - there are a lot about printing.
public class POSPrinter {
private static final Log LOG = LogFactory.getLog(POSPrinter.class);
public POSPrinter(Long billID, String printMode) {
}
/**
*
* This method prints the specified PDF to specified printer under specified
*
* job name
*
*
*
* #param filePath
* Path of PDF file
*
* #param printerName
* Printer name
*
* #param jobName
* Print job name
*
* #throws IOException
*
* #throws PrinterException
*/
public void printPDF(String filePath, String printerName, String jobName,
Integer height, Integer width) throws IOException, PrinterException {
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] pdfContent = new byte[fileInputStream.available()];
fileInputStream.read(pdfContent, 0, fileInputStream.available());
ByteBuffer buffer = ByteBuffer.wrap(pdfContent);
final PDFFile pdfFile = new PDFFile(buffer);
Printable printable = new Printable() {
public int print(Graphics graphics, PageFormat pageFormat,
int pageIndex) throws PrinterException {
int pagenum = pageIndex + 1;
if ((pagenum >= 1) && (pagenum <= pdfFile.getNumPages())) {
Graphics2D graphics2D = (Graphics2D) graphics;
PDFPage page = pdfFile.getPage(pagenum);
Rectangle imageArea = new Rectangle(
(int) pageFormat.getImageableX(),
(int) pageFormat.getImageableY(),
(int) pageFormat.getImageableWidth(),
(int) pageFormat.getImageableHeight());
graphics2D.translate(0, 0);
PDFRenderer pdfRenderer = new PDFRenderer(page, graphics2D,
imageArea, null, null);
try {
page.waitForFinish();
pdfRenderer.run();
} catch (InterruptedException exception) {
exception.printStackTrace();
}
return PAGE_EXISTS;
} else {
return NO_SUCH_PAGE;
}
}
};
PrinterJob printJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
printJob.setJobName(jobName);
Book book = new Book();
book.append(printable, pageFormat, pdfFile.getNumPages());
printJob.setPageable(book);
Paper paper = new Paper();
paper.setSize(width, height);
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
// pageFormat
pageFormat.setPaper(paper);
// PrintService[] printServices = PrinterJob.lookupPrintServices();
//
// for (int count = 0; count < printServices.length; ++count) {
//
// if (printerName.equalsIgnoreCase(printServices[count].getName())) {
//
// printJob.setPrintService(printServices[count]);
//
// break;
//
// }
//
// }
PrintService printService = PrintServiceLookup
.lookupDefaultPrintService();
printJob.setPrintService(printService);
printJob.print();
}