what i was trying to do was copying a content of file using File using File input stream and writing it in to another file
InputStream is = null;
FileOutputStream fos=null;
try{
is = new FileInputStream("D:\\helloworld.txt");
fos = new FileOutputStream("D:\\helloworld1.txt");
byte[] buffer = new byte[255];
while(is.read(buffer)>-1){
fos.write(is.read(buffer,0,buffer.length));
}
is.close();
fos.close();
}catch(Exception e){
}
}
content of helloworld:
vsdaewfscvadfdsohcdvwbuivbASJXBBfjbzx cidbv k ab SifvicvahisvcbxsiSDobhsxcb Z asvfuigevwifuvweivfb
output of helloworld is:
ΓΏ
int r=0;
while((r=is.read(buffer))>-1){
fos.write(buffer,0,r);
}
You're reading into buffer twice and writing the number of bytes read...
Related
I have a BLOB file which I have got from the DB team. I know that its a PDF document (I opened using Notepad++ and I could see the file name) and I need to convert the same using java. I have checked for few examples and I couldn't find any example where the BLOB file itself is taken as an input instead of taking directly from the DB (Resultset). Can anyone please give some pointers as to how I can accomplish this?
Thanks in advance!
I have tried below,
File file = new File("C:/Users/User1/Desktop/0LK54E33K1477e2MCEU25JV0G8MG418S007N45JU.BLOB0");
FileInputStream fis = new FileInputStream(file);
//System.out.println(file.exists() + "!!");
//InputStream in = resource.openStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
//Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
//Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
//below is the different part
File someFile = new File("C:/Users/User1/Desktop/Test.pdf");
FileOutputStream fos = new FileOutputStream(someFile);
fos.write(bytes);
fos.flush();
fos.close();
I have a requirement to store the uploaded spreadsheet to the disk. I am using the below code to do the same and receiving the file is corrupted error from the excel.
byte[] bytes = null;
File uploadedFile = new File("D://xlsxTest//BNG Issue.xlsx");
File file = new File("D://xlsxTest//sample1.xlsx");
FileOutputStream outStream = null;
InputStream inputStream = null;
try{
if(!file.exists()){
file.createNewFile();
}
outStream = new FileOutputStream(file);
if (uploadedFile != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
inputStream = new FileInputStream(uploadedFile);;
int c = 0;
while (c != -1) {
c = inputStream.read();
byteArrayOutputStream.write((char) c);
}
bytes = byteArrayOutputStream.toByteArray();
}
outStream.write(bytes);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
I tried using a file of 83KB size and the resultant file is 82.5KB.
Any help would be appreciated.
Thanks.
Try using Apace POI, Convert .xls or .xlsx file to byte array using OPCPackage and XSSFWorkbook with below code.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OPCPackage pkg = OPCPackage.open(new File(fullFileName));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
wb.write(baos);
byte[] fileContent = baos.toByteArray();
Apache POI takes care to extract all information of the excel file while converting to byte array.
I am trying to create a zip file of multiple image files. I have succeeded in creating the zip file of all the images but somehow all the images have been hanged to 950 bytes. I don't know whats going wrong here and now I can't open the images were compressed into that zip file.
Here is my code. Can anyone let me know what's going here?
String path="c:\\windows\\twain32";
File f=new File(path);
f.mkdir();
File x=new File("e:\\test");
x.mkdir();
byte []b;
String zipFile="e:\\test\\test.zip";
FileOutputStream fout=new FileOutputStream(zipFile);
ZipOutputStream zout=new ZipOutputStream(new BufferedOutputStream(fout));
File []s=f.listFiles();
for(int i=0;i<s.length;i++)
{
b=new byte[(int)s[i].length()];
FileInputStream fin=new FileInputStream(s[i]);
zout.putNextEntry(new ZipEntry(s[i].getName()));
int length;
while((length=fin.read())>0)
{
zout.write(b,0,length);
}
zout.closeEntry();
fin.close();
}
zout.close();
This is my zip function I always use for any file structures:
public static File zip(List<File> files, String filename) {
File zipfile = new File(filename);
// Create a buffer for reading the files
byte[] buf = new byte[1024];
try {
// create the ZIP file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
// compress the files
for(int i=0; i<files.size(); i++) {
FileInputStream in = new FileInputStream(files.get(i).getCanonicalName());
// add ZIP entry to output stream
out.putNextEntry(new ZipEntry(files.get(i).getName()));
// transfer bytes from the file to the ZIP file
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// complete the entry
out.closeEntry();
in.close();
}
// complete the ZIP file
out.close();
return zipfile;
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
return null;
}
Change this:
while((length=fin.read())>0)
to this:
while((length=fin.read(b, 0, 1024))>0)
And set buffer size to 1024 bytes:
b=new byte[1024];
I have a Java program that needs to read a file from a resource within the JAR and it only takes it through byte[]. My problem is converting the resource file from a folder within the project (i.e. tools/test.txt) into byte[]. I have tried the following (gave an "undefined for type" error):
final byte[] temp = new File("tools/test.txt").getBytes();
Another method I tried resulted in not being able to find the file:
FileOutputStream fos = new FileOutputStream("tools/test.txt");
byte[] myByteArray = null;
fos.write(myByteArray);
fos.close();
System.out.println("Results = " + myByteArray);
And lastly using Inputstream and BufferedReader. This actually gave the content of the file when running the program from Eclipse, but came out as null when running it as a jar (I am assuming that it is also not reading the file).
InputStream is = null;
BufferedReader br = null;
String line;
ArrayList list = new ArrayList();
try {
is = Main.class.getResourceAsStream("tools/test.txt");
br = new BufferedReader(new InputStreamReader(is));
while (null != (line = br.readLine())) {
list.add(line);
System.out.println("Output:" + line);
}
while (null == (line = br.readLine())) {
System.out.println("Error loading file:" + line);
}
}
catch (Exception ef) {
ef.printStackTrace();
System.out.println("Output:" + ef);
}
So my question is, if I have a folder named "tools" and have a file called "test.txt", what code would I use to turn it into byte[] and still work when compiled into a Jar file?
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = Main.class.getResourceAsStream("/tools/test.txt");
byte[] buffer = new byte[4096];
for (;;) {
int nread = in.read(buffer);
if (nread <= 0) {
break;
}
baos.write(buffer, 0, nread);
}
byte[] data = baos.toByteArray();
String text = new String(data, "Windows-1252");
Byte[] asByteObjects = new Byte[data.length];
for (int i # 0; i < data.length: ++i) {
asByteObjects[i] = data[i];
}
Without the heading slash the path would be relative to the package of the class. A ByteArrayOutputStream serves to collect for a byte[].
If the bytes represent text is some encoding, one can turn it into a String. Here with Windows Latin-1.
have you tried Scanner.nextByte()? make a new scanner with the file you want to parse as the input and use a for loop to create your array.
From a DB2 table I've got blob which I'm converting to a byte array so I can work with it. I need to take the byte array and create a PDF out of it.
This is what I have:
static void byteArrayToFile(byte[] bArray) {
try {
// Create file
FileWriter fstream = new FileWriter("out.pdf");
BufferedWriter out = new BufferedWriter(fstream);
for (Byte b: bArray) {
out.write(b);
}
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
But the PDF it creates is not right, it has a bunch of black lines running from top to bottom on it.
I was actually able to create the correct PDF by writing a web application using essentially the same process. The primary difference between the web application and the code about was this line:
response.setContentType("application/pdf");
So I know the byte array is a PDF and it can be done, but my code in byteArrayToFile won't create a clean PDF.
Any ideas on how I can make it work?
Sending your output through a FileWriter is corrupting it because the data is bytes, and FileWriters are for writing characters. All you need is:
OutputStream out = new FileOutputStream("out.pdf");
out.write(bArray);
out.close();
One can utilize the autoclosable interface that was introduced in java 7.
try (OutputStream out = new FileOutputStream("out.pdf")) {
out.write(bArray);
}
Read from file or string to bytearray.
byte[] filedata = null;
String content = new String(bytearray);
content = content.replace("\r", "").replace("\uf8ff", "").replace("'", "").replace("\"", "").replace("`", "");
String[] arrOfStr = content.split("\n");
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(document, page)) {
// setting font family and font size
cs.beginText();
cs.setFont(PDType1Font.HELVETICA, 14);
cs.setNonStrokingColor(Color.BLACK);
cs.newLineAtOffset(20, 750);
for (String str: arrOfStr) {
cs.newLineAtOffset(0, -15);
cs.showText(str);
}
cs.newLine();
cs.endText();
}
document.save(znaFile);
document.close();
public static String getPDF() throws IOException {
File file = new File("give complete path of file which must be read");
FileInputStream stream = new FileInputStream(file);
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;enter code here
while ((bytesRead = stream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
System.out.println("it came back"+baos);
byte[] buffer1= baos.toByteArray();
String fileName = "give your filename with location";
//stream.close();
FileOutputStream outputStream =
new FileOutputStream(fileName);
outputStream.write(buffer1);
return fileName;
}