Bufferedreader and InputStreamReader - bufferedreader

I am having trouble getting my java program to read any text files.
public static void main(String[] args) throws java.io.IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try {
long base = Long.parseLong(args[0]);
String input = br.readLine(); //read first line till the end of file
long list = Long.parseLong(input);
convertBase(base, list);
}
finally {
br.close();
}
}
The program works when I manually type the values into the command line, but when I try to use a text file it throws exceptions:
Exception in thread "main" java.lang.NumberFormatException: For input string: "baseconverion.txt"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
at FromDecimal.main(FromDecimal.java:46)
Not sure what I am doing wrong/missing.

when I try to use a text file
You mean 'when I enter a filename instead of a number'. You aren't 'try[ing]' to use a text file' at all. All you're doing is entering a filename at the console. There is nothing here that opens or reads a text file whatsoever. Java is not magic: it won't magically realize that's a filename and magically open it for you.
You need to read about file I/O in the Java Tutorial and the Javadoc.
You also shouldn't be using Long.parseLong() if your objective is to convert decimal into another base. You need to pass the original line to your conversion method.

Related

How to read flat file header and body separately in Spring Batch

i'm doing a simple batch job with Spring Batch and Spring Boot.
I need to read a flat file, separate the header data (first line) from the body data (rest of lines) for individual business logic processing and then write everything into a single file.
As you can see, the header has 5 params that have to be mapped to one class, and the body has 12 which have to be mapped to a different one.
I first thought of using FlatFileItemReader and skip the header. Then use the skippedLinesCallback to handle that line, but i couldn't figure out how to do it.
I'm new to Spring Batch and Java Config. If someone can help me writing a solution for my problem i would really aprecciate it!
I leave here the input file:
01.01.2017|SUBDCOBR|12:21:23|01/12/2016|31/12/2016
01.01.2017|12345678231234|0002342434|BORGIA RUBEN|27-32548987-9|FA|A|2062-
00010443/444/445|142,12|30/08/2017|142,01
01.01.2017|12345673201234|2342434|ALVAREZ ESTHER|27-32533987-9|FA|A|2062-
00010443/444/445|142,12|30/08/2017|142,02
01.01.2017|12345673201234|0002342434|LOPEZ LUCRECIA|27-32553387-9|FA|A|2062-
00010443/444/445|142,12|30/08/2017|142,12
01.01.2017|12345672301234|0002342434|SILVA JESUS|27-32558657-9|NC|A|2062-
00010443|142,12|30/08/2017|142,12
Cheers!
EDIT 1:
This would be my first attepmt . My "body" POJO is called DetalleFacturacion and my "header" POJO is CabeceraFacturacion. The reader I thought to do it with DetalleFacturacion pojo, so i can skip the header and treat it later... however i'm not sure how to assign header's data into CabeceraFacturacion.
public FlatFileItemReader<DetalleFacturacion> readerDetalleFacturacion(){
FlatFileItemReader<DetalleFacturacion> reader = new FlatFileItemReader<>();
reader.setLinesToSkip(1);
reader.setResource(new ClassPathResource("/inputFiles/GLEO-MN170100-PROCESO01-SUBDFACT-000001.txt"));
DefaultLineMapper<DetalleFacturacion> detalleLineMapper = new DefaultLineMapper<>();
DelimitedLineTokenizer tokenizerDet = new DelimitedLineTokenizer("|");
tokenizerDet.setNames(new String[] {"fechaEmision", "tipoDocumento", "letra", "nroComprobante",
"nroCliente", "razonSocial", "cuit", "montoNetoGP", "montoNetoG3",
"montoExento", "impuestos", "montoTotal"});
LineCallbackHandler skippedLineCallback = new LineCallbackHandler() {
#Override
public void handleLine(String line) {
String[] headerSeparado = line.split("|");
String printDate = headerSeparado[0];
String reportIdentifier = headerSeparado[1];
String tituloReporte = headerSeparado[2];
String fechaDesde = headerSeparado[3];
String fechaHasta = headerSeparado[4];
CabeceraFacturacion cabeceraFacturacion = new CabeceraFacturacion();
cabeceraFacturacion.setPrintDate(printDate);
cabeceraFacturacion.setReportIdentifier(reportIdentifier);
cabeceraFacturacion.setTituloReporte(tituloReporte);
cabeceraFacturacion.setFechaDesde(fechaDesde);
cabeceraFacturacion.setFechaHasta(fechaHasta);
}
};
reader.setSkippedLinesCallback(skippedLineCallback);
detalleLineMapper.setLineTokenizer(tokenizerDet);
detalleLineMapper.setFieldSetMapper(new DetalleFieldSetMapper());
detalleLineMapper.afterPropertiesSet();
reader.setLineMapper(detalleLineMapper);
// Test to check if it is saving correctly data in CabeceraFacturacion
CabeceraFacturacion cabeceraFacturacion = new CabeceraFacturacion();
System.out.println("Print Date:"+cabeceraFacturacion.getPrintDate());
System.out.println("Report Identif:
"+cabeceraFacturacion.getReportIdentifier());
return reader;
}
You are correct . You need to use skippedLinesCallback to handle skip lines.
You need to implement LineCallbackHandler interface and add you processing in handleLine method.
LineCallbackHandler Interface passes the raw line content of the lines in the file to be skipped. If linesToSkip is set to 2, then this interface is called twice.
This is how you can define Reader for the same.
Java Config - Spring Batch 4
#Bean
public FlatFileItemReader<POJO> myReader() {
return FlatFileItemReader<pojo>().
.setResource(new FileSystemResource("resources/players.csv"));
.name("myReader")
.delimited()
.delimiter(",")
.names("pro1,pro2,pro3")
.targetType(POJO.class)
.skippedLinesCallback(skippedLinesCallback)
.build();
}

Spring MVC outputStream

my problem is that I have a program which does make a file & stream it out to the user & I have two problem:
1) first how do change the file name & type (x.sql)
2) what if there's an exception while making the file & I want to redirect the user to an error page because my return type of my method is void when we want to write into outputstream in servlet !
my program is like this:
#RequestMapping(value = "/test/{jobid}")
public void dumpData(#PathVariable("jobid") long jobid, HttpServletResponse response) {
try {
response.setContentType("application/octet-stream");
ServletOutputStream out = response.getOutputStream();
String downloadOutput = "";
// AM I ABLE TO SET FILENAME SO THE USER DOWNLOAD THE FILE WITH THAT NAME ?
// DOES SETHEADER HELP ME IN THIS CASE ?
... (making downloadOutput String by values coming from somewhere)
out.write(downloadOutput.getBytes("UTF-8"));
out.flush();
out.close();
} catch(SomeException e){
//WHEN THE RETURN TYPE IS VOID HOW TO REDIRECT USER TO ERROR PAGE IN CASE OF SOME PROBLEM ?
//(INFO:)IF WE DEFINE STRING AS RETURN TYPE THE PROGRAM WILL GET EXCEPTION
}
Answer to your first question:
response.setHeader( "Content-Disposition", "attachment;filename=" + filename );
//for zip file
response.setContentType("application/zip");
Here is the list of mime type for various content types.
I found a solution here. You can change return type to string and return error view name in case of error otherwise return null. What I understood from the link is that returning null and return type void is similar.
What stops you from using response.sendRedirect(errorPage)?

VCF file stream to c#

I have a VCF file that contains my entire phonebook. I open it with Notepad and transferring data to windows form in c# via StreamReader. Some of vcard entries contains a row like:
"N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=42=75=72=73=61=6C=C4=B1;=4D=75=73=74=61=66=61;;;"
It looks like the line is UTF-8 code charset, but I have no idea how to convert it to a string.
Thanks for any advice.
using System.Net.Mail;
class Test
{
public static string QPDecode(String str, String encoding)
{
Attachment attachment = Attachment.CreateAttachmentFromString("", "=?" + encoding + "?Q?" + str + "?=");
return attachment.Name;
}
public static void Main(string[] args)
{
Console.WriteLine(QPDecode("=42=75=72=73=61=6C=C4=B1;=4D=75=73=74=61=66=61", "UTF-8"));
//Bursalı;Mustafa
}
}
How to extract the parts "UTF-8" and "=42=75=72=73=61=6C=C4=B1;=4D=75=73=74=61=66=61" from your file is left exercise to you :P
The property value is in quoted-printable encoding, which is a standard encoding mechanism. You may be able to find a library that can decode it for you. Also, try this SO thread.

How can use FTP in OBEX to deleting and copying a file into destination Device via bluetooth java code?

I need to replace a file with old version of it in destination device via bluetooth.
I know that OBEX(FTP and OPP) profiles is necessary to use for this.
But I don't know How can delete old version and copy new version of file in destination directory (java code).
Can you help me please?
To perform operations on files you whould firstly change to the directory where the file is.
For exampe, if you need to get to /root/directory/subdir/
you should call setPath three times
setPath(""); // to get to /root/
setPath("directory") // get to /root/directory/
setPath("subdir") // get to root/directory/subdir/
All the code written below is for J2ME
I use this method to set the path with separators (e.g. /root/dir/)
private void moveToDirectory(String dir) throws IOException {
RE r = new RE("/"); // where RE is me.regexp.RE
setDir("");
String[] dirs = r.split(dir);
for (int i = 1; i < dirs.length; i++) setDir(dirs[i]);
}
To delete a file you should open a PUT operation on it and close it, or use the delete method in ClientSession.
public void delete() throws IOException {
HeaderSet hs = cs.createHeaderSet(); // where cs is an opened ClientSession
hs.setHeader(HeaderSet.NAME, file); // file - is a filename String, no slashes should be used
cs.delete(hs);
}
If you need to replace a file you probably don't need to call delete method, just open OutputStream and write to it a new one
public OutputStream openOutputStream() throws IOException {
HeaderSet hs = cs.createHeaderSet();
hs.setHeader(HeaderSet.NAME, file);
Operation op = cs.put(hs); // Operation should be global, so you can close it after you done
return op.openOutputStream();
}
remember to close Operation after you done with the streams.

How do you save images to a Blackberry device via HttpConnection?

My script fetches xml via httpConnection and saves to persistent store. No problems there.
Then I loop through the saved data to compose a list of image url's to fetch via queue.
Each of these requests calls the httpConnection thread as so
...
public synchronized void run()
{
HttpConnection connection = (HttpConnection)Connector.open("http://www.somedomain.com/image1.jpg");
connection.setRequestMethod("GET");
String contentType = connection.getHeaderField("Content-type");
InputStream responseData = connection.openInputStream();
connection.close();
outputFinal(responseData, contentType);
}
public synchronized void outputFinal(InputStream result, String contentType) throws SAXException, ParserConfigurationException, IOException
{
if(contentType.startsWith("text/"))
{
// bunch of xml save code that works fine
}
else if(contentType.equals("image/png") || contentType.equals("image/jpeg") || contentType.equals("image/gif"))
{
// how to save images here?
}
else
{
//default
}
}
What I can't find any good documentation on is how one would take the response data and save it to an image stored on the device.
Maybe I just overlooked something very obvious. Any help is very appreciated.
Thanks
I tried following this advise and found the same thing I always find when looking up BB specific issues: nothing.
The problem is that every example or post assumes you know everything about the platform.
Here's a simple question: What line of code writes the read output stream to the blackberry device? What path? How do I retrieve it later?
I have this code, which I do not know if it does anything because I don't know where it is supposedly writing to or if that's even what it is doing at all:
** filename is determined on a loop based on the url called.
FileOutputStream fos = null;
try
{
fos = new FileOutputStream( File.FILESYSTEM_PATRIOT, filename );
byte [] buffer = new byte [262144];
int byteRead;
while ((byteRead = result.read (buffer ))!=- 1)
{
fos.write (buffer, 0, byteRead);
}
fos.flush();
fos.close();
}
catch(IOException ieo)
{
}
finally
{
if(fos != null)
{
fos.close();
}
}
The idea is that I have some 600 images pulled from a server. I need to loop the xml and save each image to the device so that when an entity is called, I can pull the associated image - entity_id.png - from the internal storage.
The documentation from RIM does not specify this, nor does it make it easy to begin figuring it out.
This issue does not seem to be addressed on this forum, or others I have searched.
Thanks
You'll need to use the Java FileOutputStream to do the writing. You'll also want to close the connection after reading the data from the InputStream (move outputFinal above your call to close). You can find all kinds of examples regarding FileOutputStream easily.
See here for more. Note that in order to use the FileOutputStream your application must be signed.

Resources