public class MakeNewFile{
static HashMap<String, User> hm = new HashMap<String, User>();
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello!!");
try{
File inputFile = new File("C:\\apache-tomcat-7.0.34\\webapps\\products\\Details.txt");
System.out.println("Done");
boolean resut = inputFile.createNewFile();
System.out.println(resut);
System.out.println("File found");
//fileInputStream = new FileInputStream(inputFile);
FileInputStream fileInputStream = new FileInputStream(inputFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
//out.println("hiii2");
hm= (HashMap)objectInputStream.readObject();
System.out.println("hiii" +hm);
if(hm.containsKey("username"))
{ String error_msg = "Username already exist as " + "usertype";}
else{
User user = new User("firstname", "lastname", "email", "username","password","usertype");
hm.put("username", user);
FileOutputStream fileOutputStream = new FileOutputStream("C:\\apache-tomcat-7.0.34\\webapps\\products\\Details.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(hm);
objectOutputStream.flush();
objectOutputStream.close();
fileOutputStream.close();
}
}
catch(Exception ex){
}
}
}
The file is not creating while running the code. Code is not executing of try block after FileInputStream. Where is the problem?
I tried one solution. File has been created but objectInputStream is not available.
After running the code locally, the exception thrown is an EOF exception - java.io.EOFException. A solution would be to do a check to see if the fileInputStream is available:
if (fileInputStream.available() > 0) {
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
//out.println("hiii2");
hm = (HashMap) objectInputStream.readObject();
}
Related
Considering I have an object from a custom class and I write it to a .dat file using FileOutputStream and ObjectOutputStream . How will I modify a object present in the file? I can only read or write objects into a file..
I know that we can create a temporary file and then renaming the file accordingly, but isnt there any other way?
I do get outputs as expected , but isnt there any other method?
Yes you can do it by using FileOutputStream & ObjectOutputStream class
class MyBean {
public String firstvalue;
public String secondvalue;
public MyBean (String firstvalue,String secondvalue){
this.firstvalue=firstvalue;
this.secondvalue=secondvalue;
}
}
public class FileSerialization {
public static void main(String[] args) {
try {
MyBean mb = new MyBean("first value", "second value");
// write object to file
FileOutputStream fos = new FileOutputStream("mybean.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(mb);
oos.close();
// read object from file
FileInputStream fis = new FileInputStream("mybean.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
MyBean result = (MyBean) ois.readObject();
ois.close();
System.out.println("One:" + result.firstvalue + ", Two:" + result.secondvalue);
result.firstvalue="Changed;";
// write object to file
fos = new FileOutputStream("mybean.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(result);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
My use case is this: when the client clicks download on a pdf, I want to edit/write some text on to the pdf using Itext pdf editor, then zip the pdf then let it download, All during the stream. I am aware of memory issue if the pdf is large etc. which won't be an issue since its like 20-50kb. I have the zipping during the stream before downloading working using byte array, now have to make the pdfeditor method also run before zipping, add some text then let the download happen.
Here is my code so far:
public class zipfolder {
public static void main(String[] args) {
try {
System.out.println("opening connection");
URL url = new URL("http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/pdfs/form.pdf");
InputStream in = url.openStream();
// FileOutputStream fos = new FileOutputStream(new
// File("enwiki.png"));
PdfEditor writepdf = new PdfEditor();
writepdf.manipulatePdf(url, dest, "field"); /// where i belive i
/// should execute the
/// editor function ?
File f = new File("test.zip");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
ZipEntry entry = new ZipEntry("newform.pdf");
zos.putNextEntry(entry);
System.out.println("reading from resource and writing to file...");
int length = -1;
byte[] buffer = new byte[1024];// buffer for portion of data from
// connection
while ((length = in.read(buffer)) > -1) {
zos.write(buffer, 0, length);
}
zos.close();
in.close();
System.out.println("File downloaded");
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
}
}
public class PdfEditor {
public String insertFields (String field, String value) {
return field + " " + value;
// System.out.println("does this work :" + field);
}
// public static final String SRC = "src/resources/source.pdf";
// public static final String DEST = "src/resources/Destination.pdf";
//
// public static void main(String[] args) throws DocumentException,
// IOException {
// File file = new File(DEST);
// file.getParentFile().mkdirs();
// }
public String manipulatePdf(URL src, String dest, String field) throws Exception {
System.out.println("test");
try {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
AcroFields form = stamper.getAcroFields();
Item item = form.getFieldItem("Name");
PdfDictionary widget = item.getWidget(0);
PdfArray rect = widget.getAsArray(PdfName.RECT);
rect.set(2, new PdfNumber(rect.getAsNumber(2).floatValue() + 20f));
String value = field;
form.setField("Name", value);
form.setField("Company", value);
stamper.close();
} catch (Exception e) {
System.out.println("Error in manipulate");
System.out.println(e.getMessage());
throw e;
}
return field;
}
}
So playing with ByteArrayOutputStream, finally got it work. passing the input stream to 'manipulatepdf' and returning 'bytedata'.
public ByteArrayOutputStream manipulatePdf(InputStream in, String field) throws Exception {
System.out.println("pdfediter got hit");
ByteArrayOutputStream bytedata = new ByteArrayOutputStream();
try {
PdfReader reader = new PdfReader(in);
PdfStamper stamper = new PdfStamper(reader, bytedata);
AcroFields form = stamper.getAcroFields();
Item item = form.getFieldItem("Name");
PdfDictionary widget = item.getWidget(0);
PdfArray rect = widget.getAsArray(PdfName.RECT);
rect.set(2, new PdfNumber(rect.getAsNumber(2).floatValue() + 20f));
String value = field;
form.setField("Name", value);
form.setField("Company", value);
stamper.close();
} catch (Exception e) {
System.out.println("Error in manipulate");
System.out.println(e.getMessage());
throw e;
}
return bytedata;
}
public String editandzip (String data, String Link) {
try {
System.out.println("opening connection");
URL url = new URL(Link);
InputStream in = url.openStream();
System.out.println("in : "+ url);
//String data = "working ok with main";
PdfEditor writetopdf = new PdfEditor();
ByteArrayOutputStream bao = writetopdf.manipulatePdf(in, data);
byte[] ba = bao.toByteArray();
File f = new File("C:/Users/JayAcer/workspace/test/test.zip");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
ZipEntry entry = new ZipEntry("newform.pdf");
entry.setSize(ba.length);
zos.putNextEntry(entry);
zos.write(ba);
zos.close();
in.close();
System.out.println("File downloaded");
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
return data;
}
}
I have created an app whereby the user can save, edit and delete notes and it would be stored in the applications private storage area. the data that is being stored needs to be encrypted however I am new to programming and do not know much about how to do this so if anyone can advise please? I will put the code below for the method that is used to save the notes but for security reasons, encryption is required, what would be the easiest method to use for a beginner?
public class Utilities {
public static final String FILE_EXTENSION = ".bin";
public static boolean saveNote(Context context, Notes notes){
String fileName = String.valueOf(notes.getDateTime()) + FILE_EXTENSION;
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = context.openFileOutput(fileName, context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(notes);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false; //tell the user something went wrong
}
return true;
}
public static ArrayList<Notes> getSavedNotes(Context context) {
ArrayList<Notes> notes = new ArrayList<>();
File filesDir = context.getFilesDir();
filesDir.getAbsolutePath();
ArrayList<String> noteFiles = new ArrayList<>();
for(String file : filesDir.list()) {
if(file.endsWith(FILE_EXTENSION)) {
noteFiles.add(file);
}
}
FileInputStream fis;
ObjectInputStream ois;
for(int i = 0; i < noteFiles.size(); i++) {
try{
fis = context.openFileInput(noteFiles.get(i));
ois = new ObjectInputStream(fis);
notes.add((Notes)ois.readObject());
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
return notes;
}
public static Notes getNoteByName(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
Notes notes;
if(file.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try {
fis = context.openFileInput(fileName);
ois = new ObjectInputStream(fis);
notes = (Notes) ois.readObject();
fis.close();
ois.close();
} catch(IOException | ClassNotFoundException e){
e.printStackTrace();
return null;
}
return notes;
}
return null;
}
public static void deleteNote(Context context, String fileName) {
File Dir = context.getFilesDir();
File file = new File(Dir, fileName);
if (file.exists()) file.delete();
}
public static void main(String[] args) {
try {
String key = "squirrel123"; // needs to be at least 8 characters for DES
FileInputStream fis = new FileInputStream("original.txt");
FileOutputStream fos = new FileOutputStream("encrypted.txt");
encrypt(key, fis, fos);
FileInputStream fis2 = new FileInputStream("encrypted.txt");
FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
decrypt(key, fis2, fos2);
} catch (Throwable e) {
e.printStackTrace();
}
}
public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}
public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
}
public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, desKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}
public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}
}
Edit:
I have now added an example des encryption below the existing code it now looks like this, also how would I know the data is actually encrypted?
public class Utilities {
public static final String FILE_EXTENSION = ".bin";
public static boolean saveNote(Context context, Notes notes){
String fileName = String.valueOf(notes.getDateTime()) + FILE_EXTENSION;
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = context.openFileOutput(fileName, context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(notes);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false; //tell the user something went wrong
}
return true;
}
public static ArrayList<Notes> getSavedNotes(Context context) {
ArrayList<Notes> notes = new ArrayList<>();
File filesDir = context.getFilesDir();
filesDir.getAbsolutePath();
ArrayList<String> noteFiles = new ArrayList<>();
for(String file : filesDir.list()) {
if(file.endsWith(FILE_EXTENSION)) {
noteFiles.add(file);
}
}
FileInputStream fis;
ObjectInputStream ois;
for(int i = 0; i < noteFiles.size(); i++) {
try{
fis = context.openFileInput(noteFiles.get(i));
ois = new ObjectInputStream(fis);
notes.add((Notes)ois.readObject());
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
return notes;
}
public static Notes getNoteByName(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
Notes notes;
if(file.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try {
fis = context.openFileInput(fileName);
ois = new ObjectInputStream(fis);
notes = (Notes) ois.readObject();
fis.close();
ois.close();
} catch(IOException | ClassNotFoundException e){
e.printStackTrace();
return null;
}
return notes;
}
return null;
}
public static void deleteNote(Context context, String fileName) {
File Dir = context.getFilesDir();
File file = new File(Dir, fileName);
if(file.exists()) {
file.delete();
}
}
}
DES (Data Encryption Standard) is pretty common for simple tasks like yours. There are a bunch of tutorials online for how to use it. Here's one example I've used: http://www.avajava.com/tutorials/lessons/how-do-i-encrypt-and-decrypt-files-using-des.html
There was another thread where a user shared a more advanced method, Password-Based Key Derivation Function, that is also worth trying. Here's the link: How to encrypt and salt the password using BouncyCastle API in Java?
private void saveFormActionPerformed(java.awt.event.ActionEvent evt) {
name = nameFormText.getText();
surname = surnameFormText.getText();
age = Integer.parseInt(ageFormText.getText());
stadium = stadiumFormText.getText();
Venues fix = new Venues();
fix.setName(name);
fix.setSurname(surname);
fix.setAge(age);
fix.setStadium(stadium);
File outFile;
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
outFile = new File("output.data");
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(fix);
JOptionPane.showMessageDialog(null, "File written successfully");
oStream.close();
} catch (IOException e) {
System.out.println(e);
}
}
This is what I have so far. Any ideas on what I could do with it to append the file if it's already created?
You have first to check if the file exists before, if not create a new one. To learn how to append object to objectstream take a look at this question.
File outFile = new File("output.data");
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
if(!outFile.exists()) outFile.createNewFile();
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(fix);
JOptionPane.showMessageDialog(null, "File written successfully");
oStream.close();
} catch (IOException e) {
System.out.println(e);
}
Using Java 7, it is simple:
final Path path = Paths.get("output.data");
try (
final OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
final ObjectOutputStream objOut = new ObjectOutputStream(out);
) {
// work here
} catch (IOException e) {
// handle exception here
}
Drop File!
I am using Weka SMO to classify my training data and I want to save and load easily to/from file my SMO model. I have created a save method in order to store Classifier to file. My code is the following:
private static Classifier loadModel(Classifier c, String name, File path) throws Exception {
FileInputStream fis = new FileInputStream("/weka_models/" + name + ".model");
ObjectInputStream ois = new ObjectInputStream(fis);
return c;
}
private static void saveModel(Classifier c, String name, File path) throws Exception {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new FileOutputStream("/weka_models/" + name + ".model"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
oos.writeObject(c);
oos.flush();
oos.close();
}
My problem is, how to convert ObjectInputStream to Classifier object.
Ok it was an easy one, I ve just had to use readObject.
private static Classifier loadModel(File path, String name) throws Exception {
Classifier classifier;
FileInputStream fis = new FileInputStream(path + name + ".model");
ObjectInputStream ois = new ObjectInputStream(fis);
classifier = (Classifier) ois.readObject();
ois.close();
return classifier;
}