For a college project i have to save a hashmap of Lists to a binary file. Then i have to be able to load it again but im having a bit of trouble. It will save my file but will not load it. Here is my code:
This is Saving:
private static void storeRec()
{
try
{
File f = new File("recommendation.dat");
if(!f.exists())
{
f.createNewFile();
}
FileOutputStream fos=new FileOutputStream(f);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(localStore);
oos.flush();
oos.close();
fos.close();
System.out.println("Recommendation read to File");
}
catch (IOException ex)
{
Logger.getLogger(Project2.class.getName()).log(Level.SEVERE, null, ex);
}
}
This is the loading code :
List<Recommendation> newmovies = new ArrayList<>();
try
{
File f = new File("recommendation.dat");
if(f.exists())
{
DataInputStream dis = new DataInputStream(new FileInputStream(f));
/*FileInputStream streamIn = new FileInputStream(f);
ObjectInputStream dis = new ObjectInputStream(streamIn);*/
while(dis.available()>0)
{
byte[] titleBytes = new byte[32];
dis.read(titleBytes);
String title = new String(titleBytes);
byte[] queryBytes = new byte[32];
dis.read(queryBytes);
String query = new String(queryBytes);
byte[] directorBytes = new byte[32];
dis.read(directorBytes);
String director = new String(directorBytes);
byte[] summaryBytes = new byte[64];
dis.read(summaryBytes);
String summary = new String(summaryBytes);
byte[] categoryBytes = new byte[18];
dis.read(categoryBytes);
String category = new String(categoryBytes);
//String category = dis.readUTF();
double rating = dis.readDouble();
int release = dis.readInt();
byte[] castBytes = new byte[64];
dis.read(castBytes);
String cast= new String(castBytes);
ArrayList<String> castArrayList = new ArrayList<>(Arrays.asList(cast.split(",")));
int myRating = dis.readInt();
byte[] commentsBytes = new byte[32];
dis.read(commentsBytes);
String myComments = new String(commentsBytes);
newmovies.add(new Recommendation(title,query,director,summary,release,category,rating,castArrayList,myRating,myComments));
//System.out.println(newmovies);
localStore.put(query, newmovies);
}
}
LocalStore is a hashmap i would like to add the data from the file to. The key is the Query. For some reason it will not add to the map
Any help would be very much appreciated.
You have to use an ObjectInputStream on a file created by ObjectOutputStream, and readObject()to read an object written by writeObject().
And available() is not a valid test for end of stream. See the Javadoc. You have to catch EOFException.
Related
Java's GZIPInputStream and Apache's GzipCompressorInputStream both disable themselves as soon as they reach EOF.
I want to be able to decompress a file which is being written to and when there's not enough data available for decompression or there is no data at all to simply get -1 and be able to keep trying to read until data becomes available as with a regular FileInputStream.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/zip/GZIPInputStream.html
https://commons.apache.org/proper/commons-compress/apidocs/org/apache/commons/compress/compressors/gzip/GzipCompressorInputStream.html
Here's a main method showing the problem.
I'd like to be able to keep reading once more data is available in the file. I compress the strings "a" and "b". I write the gzipped "a" to the file then read it. I then write the gzipped "b" to the file but the same InputStream will never be able to read it because it disabled itself when it reached the end of file after reading the gzipped "a".
public static void main(String[] args) throws IOException {
ByteArrayOutputStream firstByteArrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream firstGzipOutputStream = new GZIPOutputStream(firstByteArrayOutputStream);
firstGzipOutputStream.write("a".getBytes(StandardCharsets.UTF_8));
firstGzipOutputStream.close();
byte[] firstGzippedBytes = firstByteArrayOutputStream.toByteArray();
ByteArrayOutputStream secondByteArrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream secondGzipOutputStream = new GZIPOutputStream(secondByteArrayOutputStream);
secondGzipOutputStream.write("b".getBytes(StandardCharsets.UTF_8));
secondGzipOutputStream.close();
byte[] secondGzippedBytes = secondByteArrayOutputStream.toByteArray();
Path combiner = Files.createTempFile("gziptest", "gz");
FileOutputStream fileWriter = new FileOutputStream(combiner.toFile(), false);
fileWriter.write(firstGzippedBytes);
fileWriter.close();
InputStream b = new GZIPInputStream(new FileInputStream(combiner.toFile()));
int fromFile = b.read();
while (fromFile != -1) {
System.out.print((char) fromFile);
fromFile = b.read();
}
FileOutputStream fileAppender = new FileOutputStream(combiner.toFile(), true);
fileAppender.write(secondGzippedBytes);
fileAppender.close();
fromFile = b.read();
while (fromFile != -1) {
System.out.print((char) fromFile);
fromFile = b.read();
}
}
I'd rather not have to implement my own inflater...
Contrast that with the following using a simple FileInputStream with no compression. All the data is read - the stream starts returning data once it is written to the file.
public static void main(String[] args) throws IOException {
ByteArrayOutputStream firstByteArrayOutputStream = new ByteArrayOutputStream();
firstByteArrayOutputStream.write("a".getBytes(StandardCharsets.UTF_8));
firstByteArrayOutputStream.close();
byte[] firstGzippedBytes = firstByteArrayOutputStream.toByteArray();
ByteArrayOutputStream secondByteArrayOutputStream = new ByteArrayOutputStream();
secondByteArrayOutputStream.write("b".getBytes(StandardCharsets.UTF_8));
secondByteArrayOutputStream.close();
byte[] secondGzippedBytes = secondByteArrayOutputStream.toByteArray();
Path combiner = Files.createTempFile("gziptest", "gz");
FileOutputStream fileWriter = new FileOutputStream(combiner.toFile(), false);
fileWriter.write(firstGzippedBytes);
fileWriter.close();
InputStream b = new FileInputStream(combiner.toFile());
int fromFile = b.read();
while (fromFile != -1) {
System.out.print((char) fromFile);
fromFile = b.read();
}
FileOutputStream fileAppender = new FileOutputStream(combiner.toFile(), true);
fileAppender.write(secondGzippedBytes);
fileAppender.close();
fromFile = b.read();
while (fromFile != -1) {
System.out.print((char) fromFile);
fromFile = b.read();
}
}
//Or any other solution to saving multipartfile into DB.
I tried with this way but getting error.
File fileOne = new File("file.getOrignalFileName");//what should be kept inside this method
byte[] bFile = new byte[(int) fileOne.length()];
try {
FileInputStream fileInputStream = new FileInputStream(fileOne);
//convert file into array of bytes
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
questionDao.saveImage(bFile);
MultipartFile file;
byte [] byteArr=file.getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArr);
//Start Photo Upload with Adhaar No//
if (simpleLoanDto.getPic() != null && simpleLoanDto.getAdharNo() != null) {
String ServerDirPath = globalVeriables.getAPath() + "\\";
File ServerDir = new File(ServerDirPath);
if (!ServerDir.exists()) {
ServerDir.mkdirs();
}
// Giving File operation permission for LINUX//
IOperation.setFileFolderPermission(ServerDirPath);
MultipartFile originalPic = simpleLoanDto.getPic();
byte[] ImageInByte = originalPic.getBytes();
FileOutputStream fosFor = new FileOutputStream(
new File(ServerDirPath + "\\" + simpleLoanDto.getAdharNo() + "_"+simpleLoanDto.getApplicantName()+"_.jpg"));
fosFor.write(ImageInByte);
fosFor.close();
}
//End Photo Upload with Adhaar No//
I am trying to add serilization and deserialization to my app. I have already added serization which makes it into a textfileThis problem is involving ArrayLists. I was browsing this page: http://www.vogella.com/articles/JavaSerialization/article.html when I saw this code:
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
p = (Person) in.readObject();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(p);
}
I was confused on this line:
p = (Person) in.readObject();
How do I make this line an ArrayList when creating an ArrayList is not as simple as that:
List<String> List = new ArrayList<String>();
Thanks for the help in advance!
I took the code directly from the website that you provided a link for and modified it for an ArrayList. You mention "How do I make this line an ArrayList when creating an ArrayList is not as simple as that", I say creating an ArrayList is as simple as that.
public static void main(String[] args) {
String filename = "c:\\time.ser";
ArrayList<String> p = new ArrayList<String>();
p.add("String1");
p.add("String2");
// Save the object to file
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(p);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// Read the object from file
// Save the object to file
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
p = (ArrayList<String>) in.readObject();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(p);
}
prints out [String1, String2]
Have you written a whole ArrayList as an object in the file?
Or have you written Persons object that were in an ArrayList in a loop in the file?
How can i append two audio files in android. I tried this but it does not work. pls give me a soln.I need to concatenate the files from sdcard that ts A.mp3 and B.mp3 .When i merge concatenate method calls i want both of them as a single file in sdcard that is C.mp3........
File original= new File("/mnt/sdcard/A.mp3");
File temp=new File("/mnt/sdcard/B.mp3");
Log.i("...............",""+path);
try {
File outFile= new File("/mnt/sdcard/C.mp3 ");
DataOutputStream out=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
// FileOutputStream out=new FileOutputStream(outFile);
//OutputStream out = new FileOutputStream(original,true);
int m,n;
m=(int) temp.length();
n=(int) original.length();
byte[] buf1 = new byte[m];
byte[] buf2 = new byte[n];
byte[] outBytes = new byte[m+n];
DataInputStream dis1=new DataInputStream( new BufferedInputStream(new FileInputStream(original)));
DataInputStream dis2=new DataInputStream( new BufferedInputStream(new FileInputStream(temp)));
dis1.read(buf1, 0, m);
dis1.close();
dis2.readFully(buf2, 0, n);
dis2.close();
out.write(buf1);
out.write(buf2);
out.flush();
//in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I need to combine The File A.mp3,B.mp3 to C.mp3....
In addition to the answer of knowbody, you can refer to the mp3 file format specification for more information HERE and HERE.
There are a lot of things you should consider when stitching two mp3 files. The least to say is that they need to be encoded by the same program, with the same settings or if we're speaking about voice, to be taken from the same microphone, set with the same settings etc.
import java.io.*;
public class TwoFiles
{
public static void Main(String args[]) throws IOException
{
FileInputStream fistream1 = new FileInputStream("C:\\Temp\\1.mp3");
FileInputStream fistream2 = new FileInputStream("C:\\Temp\\2.mp3");
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
FileOutputStream fostream = new FileOutputStream("C:\\Temp\\final.mp3");
int temp;
while( ( temp = sistream.read() ) != -1)
{
fostream.write(temp);
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}
I hope is clear
After some research it seems that I should be modifying my Object into bytes before sending. As my code is rather extensive i will give it in demonstrative pieces. I have the problem that nothing happens on successful completion of the program.
SAVE and SET variables are named in the following manner within the private void
int count = jTable1.getRowCount();
for(int i=0;i<count;i++){
//SET0
SET0 = new Object[1][count];
SET0[0][i] = txt.getText();
ByteArrayOutputStream baosSET0 = new ByteArrayOutputStream();
ObjectOutputStream oosSET0 = new ObjectOutputStream(baosSET0);
oosSET0.writeObject(SET0.toString());
byte[] SET0asBytes = baosSET0.toByteArray();
ByteArrayInputStream baisSET0 = new ByteArrayInputStream(SET0asBytes);
AND
SAVE = new Object[1][count];
SAVE[0][i] = jTable1.getModel().getValueAt(i,0);
ByteArrayOutputStream baosSAVE = new ByteArrayOutputStream();
ObjectOutputStream oosSAVE = new ObjectOutputStream(baosSAVE);
oosSAVE.writeObject(SAVE.toString());
byte[] SAVEasBytes = baosSAVE.toByteArray();
ByteArrayInputStream baisSAVE = new ByteArrayInputStream(SAVEasBytes);
Which leads into my SQL query:
String sqla1 = "INSERT INTO MIT(MTY_KOD,MTY_TYY,MTY_ALU,MTY_PAR1,MTY_PAR2,MTY_TOL,MTY_KAN,MTY_DATE) values(?,?,?,?,?,?,?,?);";
try{
pst = conn.prepareStatement(sqla1);
pst.setBinaryStream(1, baisSET0 , SET0asBytes.length);
pst.setBinaryStream(2, baisSET2, SET2asBytes.length);
pst.setBinaryStream(3, baisSET1, SET1asBytes.length);
pst.setBinaryStream(4, baisSAVE, SAVEasBytes.length);
pst.setBinaryStream(5, baisSAVE3, SAVE3asBytes.length);
pst.setBinaryStream(6, baisSAVE5, SAVE5asBytes.length);
pst.setBinaryStream(7, baisSET3, SET3asBytes.length);
pst.setBinaryStream(8, baisSET2, SET2asBytes.length);
pst.executeUpdate();}
catch (Exception e) {
System.out.println(e);
}
Event is triggered from:
if(txt.getText().isEmpty()){
}else{
try{
INSERT();}
catch(IOException ex){
System.out.println(ex);
}
}
The error i get is:
com.microsoft.sqlserver.jdbc.SQLServerException: The stream value is not the specified length. The specified length was 35, the actual length is 0.
Can anyone direct me on how to fix this error... or a different method of saving the information? Thank you.
I suspect you need to close your ObjectOutputStream.
From the doc:
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(12345);
oos.writeObject("Today");
oos.writeObject(new Date());
oos.close(); // <-- my emphasis!