I'm writing a fairly simple program, which needs to save some simple data between runs. This data is defined by UserData, outlined below:
public class UserData implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3542558265070011448L;
public static ArrayList<String> projectList;
public static ArrayList<Bill> billList;
public static String userName;
public static String userEmail;
public UserData() {
}
public UserData(String name, String email) {
super();
userName = name;
userEmail = email;
projectList = new ArrayList<String>();
billList = new ArrayList<Bill>();
}
public String getUserName() {
return userName;
}
public String getUserEmail() {
return userEmail;
}
public ArrayList<Bill> getBillList() {
return billList;
}
public ArrayList<String> getProjectList() {
return projectList;
}
public void setBillList(Bill theBill) {
billList.add(theBill);
}
public void setProjectList(String projectName) {
projectList.add(projectName);
}
}
I Then have a class which handles serializing/deserializing of this data and it's instance to a file, with the various calls done directly or indirectly by events in a separate Gui Class. This is it:
public class FileHandler implements Serializable {
/**
*
*/
private static final long serialVersionUID = 473118590700911358L;
private static JFileChooser fileChooser;
public UserData myUserData;
public FileHandler() throws ClassNotFoundException, IOException {
fileChooser = new JFileChooser();
initData();
}
public FileHandler(UserData newUser) {
fileChooser = new JFileChooser();
myUserData = newUser;
System.out.println("Entered User: " + myUserData.getUserName());
System.out.println("Entered User: " + myUserData.getUserEmail());
}
private void createProgramData() throws FileNotFoundException, IOException {
FileOutputStream fileOut = new FileOutputStream("data\\ProgramData.diy");
ObjectOutputStream encoderp = new ObjectOutputStream(fileOut);
System.out.println("createProgramData: " + myUserData.getUserName());
System.out.println("createProgramData: "+ myUserData.getUserEmail());
encoderp.writeObject(myUserData);
encoderp.close();
fileOut.close();
}
public void exportData() throws FileNotFoundException, IOException {
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
final int selectedFile = fileChooser.showOpenDialog(null);
ObjectOutputStream encodere = null;
if (selectedFile == JFileChooser.APPROVE_OPTION) {
final File selectedPath = fileChooser.getSelectedFile();
FileOutputStream fileOut = new FileOutputStream(selectedPath + "\\UserData.diy");
encodere = new ObjectOutputStream(fileOut);
System.out.println("Writing Data: " + myUserData.getUserName());
System.out.println("Writing Data: " + myUserData.getUserEmail());
encodere.writeObject(myUserData);
encodere.close();
fileOut.close();
}
}
public void importData() throws ClassNotFoundException, IOException {
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
final int selectedFile = fileChooser.showSaveDialog(null);
ObjectInputStream decoderim = null;
if (selectedFile == JFileChooser.APPROVE_OPTION) {
final File selectedPath = fileChooser.getSelectedFile();
FileInputStream fileIn = new FileInputStream(selectedPath);
decoderim = new ObjectInputStream(fileIn);
myUserData = (UserData)decoderim.readObject();
decoderim.close();
fileIn.close();
System.out.println("importing Data: " + myUserData.getUserEmail());
System.out.println("importing Data: " + myUserData.getUserName());
}
}
private void initData() throws IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream("data\\ProgramData.diy");
ObjectInputStream decoderi = new ObjectInputStream(fileIn);
myUserData = (UserData)decoderi.readObject();
decoderi.close();
fileIn.close();
System.out.println("initializing Data: " + myUserData.getUserName());
System.out.println("Initializing Data: " + myUserData.getUserEmail());
}
public UserData getUserData() {
return myUserData;
}
A problem I'm having with the ObjectInputStream and possibly ObjectOutputStream seems to be that when I serialize UserData, exit my program, and then re-enter and try to import that file, the instance of UserData remains unchanged. I can't seem to figure out what I'm missing. Even pointing out something I've overlooked helps.
UserData only has static fields, and static fields aren't serialized. From the look of your code they should all be instance members. Don't make anything static unless you know exactly why you are doing so.
Related
I am kind of stuck, I usually know how to create single csv, it looks like I am missing or disconnecting from this code. I am not able to create multiple csv file from Pojo class. The file usually is more than 15mb, but I need to split into multiple csv file like 5mb each. Any suggestion would be great helped. Here is sample code that I am trying but failing.
public static void main(String[] args) throws IOException {
getOrderList();
}
public static void getOrderList() throws IOException {
List<Orders> ordersList = new ArrayList<>();
Orders orders = new Orders();
orders.setOrderNumber("1");
orders.setProductName("mickey");
Orders orders1 = new Orders();
orders1.setOrderNumber("2");
orders1.setProductName("mini");
ordersList.add(orders);
ordersList.add(orders1);
Object [] FILE_HEADER = {"orderNumber","productName"};
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int rowCount = 0;
int fileCount = 1;
try {
BufferedWriter fileWriter = new BufferedWriter(new OutputStreamWriter(byteArrayOutputStream));
CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter,
CSVFormat.DEFAULT.withRecordSeparator("\n"));
csvFilePrinter.printRecord(FILE_HEADER);
for (Orders patient : ordersList) {
rowCount++;
patient.getOrderNumber();
patient.getProductName();
if (rowCount <= 1) {
csvFilePrinter.printRecord(patient);
csvFilePrinter.flush();
}
if (rowCount > 1 ) {
csvFilePrinter.printRecord(patient);
fileCount++;
csvFilePrinter.flush();
}
}
} catch (IOException e) {
throw new RuntimeException("Cannot generate csv file", e);
}
byte[] csvOutput = byteArrayOutputStream.toByteArray();
OutputStream outputStream = null;
outputStream = new FileOutputStream("demos" + fileCount + ".csv");
byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(csvOutput);
byteArrayOutputStream.writeTo(outputStream);
}
public static class Orders {
private String orderNumber;
private String productName;
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}
I am working on a school project that basically allows the user to create, edit and display students. I have a createStudent() that writes the info into the file using Scanner and ObjectOutputStream. The displayStudent() reads the data from the file using ObjectInputStream and displays it. The idea with editStudent() is to ask the user to enter the ID of the student they want to edit and then change the date and write it back to the file, what I have been trying to do is read the data from the file using ObjectInputStream and then assign that data into ArrayList or HashMap, I think I will be using ArrayList because HashMap is unordered. When I try to add the data from the file into ArrayList I get the following error:
java.io.EOFException at java.base/java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:3231) at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1663) at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:519) at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:477) at MidTermProject.editStudent(MidTermProject.java:194) at MidTermProject.main(MidTermProject.java:381)
Here is my code for editStudent():
public static void editStudent() throws IOException {
int editID;
String student;
ArrayList<String> studentEdit = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
FileInputStream fstream = new FileInputStream("studentInfo.dat");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
System.out.print("Enter the ID of the student you would like to edit: ");
editID = keyboard.nextInt();
try {
student = (String) inputFile.readObject();
studentEdit.add(student);
System.out.print(studentEdit);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
///Added create student method
public static void createStudent() throws IOException {
File file = new File("studentInfo.dat");
boolean append = file.exists();
Scanner keyboard = new Scanner(System.in);
try (
FileOutputStream fout = new FileOutputStream(file, append);
MidTermProject oout = new MidTermProject(fout, append);
) {
id = idGenerator.getAndIncrement();
String convertedId = Integer.toString(getId());
oout.writeObject(convertedId);
System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
FullName = keyboard.nextLine();
oout.writeObject(FullName);
System.out.print("Address: ");
address = keyboard.nextLine();
oout.writeObject(address);
System.out.print("City: ");
city = keyboard.nextLine();
oout.writeObject(city);
System.out.print("State: ");
state = keyboard.nextLine();
oout.writeObject(state);
oout.close();
System.out.println("Done!\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here is the class code for MidTermProject
public class MidTermProject extends ObjectOutputStream {
private boolean append;
private boolean initialized;
private DataOutputStream dout;
static AtomicInteger idGenerator = new AtomicInteger(0001);
static int id;
public static String FullName;
public static String address;
public static String city;
public static String state;
public static String className;
public static String instructor;
public static String department;
public static String classNumber;
public static String courseNumber;
public static String year;
public static String semester;
public static String grade;
public static String studentID;
public static String courseID;
public static String enrollmentID;
public static HashMap<String, Integer> map = new HashMap<>();
Scanner keyboard = new Scanner(System.in);
protected MidTermProject(boolean append) throws IOException, SecurityException {
super();
this.append = append;
this.initialized = true;
}
public MidTermProject(OutputStream out, boolean append) throws IOException {
super(out);
this.append = append;
this.initialized = true;
this.dout = new DataOutputStream(out);
this.writeStreamHeader();
}
#Override
protected void writeStreamHeader() throws IOException {
if (!this.initialized || this.append) return;
if (dout != null) {
dout.writeShort(STREAM_MAGIC);
dout.writeShort(STREAM_VERSION);
}
}
If think you are misusing serialization: whether Serialization is bad or good is another matter, but that should be something like that:
List<Student> students = ... ;
try (OuputStream os = Files.newOutputStream(Paths.get("out"));
ObjectOutputStream oos = new ObjectOutputStream(os)) {
oos.writeObject(students);
}
Reading it should be as simple as:
try (InputStream is = Files.newInputStream(Paths.get("out"));
ObjectInputStream iis = new ObjectInputStream(is)) {
List<Student> students = iis.readObject(students);
}
You must ensure that Student is Serializable and have only Serializable or transient fields:
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private String fullName;
private String address;
private transient String wontBeExported;
...
}
Notice that the fields are not static: serialization is about serializing an object and its fields. Static fields are not part of any instance.
You should also not have to extends the ObjectOutputStream class, or if you do, you must ensure that you read the object written by your implementation of ObjectOutputStream is symmetric with the ObjectInputStream you are using:
If you write an header, your ObjectInputStream must read said header.
If you write an object, your ObjectInputStream must read said object.
And the order is important: you can't read the object before the header is read.
You should also read the Java tutorial: https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html
I have a 'Person' class where i stored data like name, surname etc. I make 5 object type Person, add them to ArrayList, and save this ArrayList to file. Next i'm loading from this file ArrayList and i have 5 person. Problem is when i want save again for example 10 object Person. When i'm loading ArrayList from file i'm getting only 5 person from first writing. If i repeat this still i will have load data from first writing to this file. How i can fix this ?
public class Data {
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons(5);
Data.loadPersons();
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
System.out.println("\n-----------\nNext Round\n-----------\n");
Data.savePersons(10);
Data.loadPersons();
}
/** Save a couple of Person Object to file C:/data.ser */
public static void savePersons(int noOfPersonToSave) throws IOException {
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object and add them to ArrayList 'persons' for example */
for (int i = 0; i < noOfPersonToSave; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890" +i);
persons.add(personTest);
}
try {
fout = new FileOutputStream("C:\\data.ser", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(persons);
System.out.println("Saving '" + persons.size() + "' Object to Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR: " + ex.getMessage());
} finally {
if (oos != null) {
oos.close();
}
}
}
/** Load previously saved a couple of Person Object in file C:/data.ser */
public static void loadPersons() throws IOException {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("C:\\data.ser");
ois = new ObjectInputStream(fis);
persons = (List<Person>) ois.readObject();
//persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" + persons.size() + "' Object from Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("loadPersons() = OK");
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
} finally {
if (ois != null) {
ois.close();
}
}
}}
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private String mail;
private String telephone;
public Person(String n, String s, String m, String t) {
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}}
new FileOutputStream("C:\\data.ser", true)
You're passing true for the append parameter. So you're appending a list of 10 persons to the file, after the already existing list of 5 people. And since you only read one list, you read the first you wrote, which contains 5 persons.
Pass false instead of true.
I am trying to download multiple files from a remote server using multiple threads. However when I am using multiple threads I get
java.lang.IOException : Pipes closed.
The same code works fine when i am using exactly one thread.
Is it not possible to download multiple files simultaneously from the same remote server using JSch?
SftpTest.java
public class SftpTest {
private static List<SftpAccessor> accessorList = new ArrayList<SftpAccessor>();
private static List<Payload> files = new ArrayList<Payload>();
private static ExecutorService writerThreadPool = Executors.newFixedThreadPool(10);
public static void main(String args[]) throws JSchException, InterruptedException {
SSH srcServer = new SSH();
srcServer.setHostname("10.22.65.140");
srcServer.setKey("D:\\jars\\dmwvmcol01.ec2user.pem");
srcServer.setPort("22");
srcServer.setUsername("ec2-user");
SftpAccessor acc = new SftpAccessor(srcServer);
accessorList.add(acc);
files.addAll(acc.ls("/data/test/src", false, "*", 1));
for (Payload file : files) {
writerThreadPool.submit(new LocalWriterThread(file));
}
writerThreadPool.shutdown();
writerThreadPool.awaitTermination(20, TimeUnit.MINUTES);
}}
LocalWriterThread.java
public class LocalWriterThread implements Callable<String> {
private Payload payload;
public LocalWriterThread(Payload payload) {
this.payload = payload;
}
public String call() throws Exception {
String dest = "D:\\output\\jobsystemnew";
System.out.println(payload.getFilename());
File file = new File(dest + "/" + payload.getFilename());
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
copy(payload.getInputStream(), fos);
payload.setInputStream(null);
return "";
}
private void copy(InputStream is, OutputStream os) throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
System.out.println("Started Copying file : " + payload.getFilename());
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
while (bis.read(buffer) != -1) {
bos.write(buffer);
}
bos.flush();
System.out.println("Finished Copying file : " + payload.getFilename());
}
finally {
System.out.println("Closing input stream for " + payload.getFilename());
bis.close();
bos.close();
/*
* try { if (is != null) { is.close(); } } catch (Exception e) { System.out.println(" " + e + " : " + e.getMessage() + " unable to close input stream : " + payload.getFilename());
* e.printStackTrace(); }
*/
/*
* try { if (os != null) { os.close(); } } catch (Exception e) { System.out.println(" " + e + " : " + e.getMessage() + " unable to close output stream : " + payload.getFilename());
* e.printStackTrace(); }
*/
}
}}
SSH.java
public class SSH {
String hostname;
String port;
String username;
String key;
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
} }
SftpAccessor.java
public class SftpAccessor {
private JSch jsch = new JSch();
private ChannelSftp channelSftp = null;
private Session session = null;
String errorMsg = null;
public SftpAccessor(SSH ssh) throws JSchException {
jsch.addIdentity(ssh.getKey());
session = jsch.getSession(ssh.getUsername(), ssh.getHostname(), Integer.parseInt(ssh.getPort()));
session.setHostKeyAlias(ssh.getKey());
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
}
public List<Payload> ls(String directory, boolean recursive, String filemask, int delayMinutes) {
List<Payload> files = new ArrayList<Payload>();
try {
channelSftp.cd(directory);
#SuppressWarnings("unchecked")
Vector<ChannelSftp.LsEntry> entries = channelSftp.ls(filemask);
for (ChannelSftp.LsEntry entry : entries) {
try {
if (entry.getAttrs().isDir()) {
if (recursive) {
List<Payload> filesToAdd = ls(directory + "/" + entry.getFilename(), recursive, filemask, delayMinutes);
files.addAll(filesToAdd);
}
}
else {
Date lastmodified = new Date(entry.getAttrs().getMTime() * 1000L);
Date currdate = new Date(new Date().getTime() - (delayMinutes * 60 * 1000L));
if (lastmodified.before(currdate)) {
String filename = entry.getFilename();
entry.getAttrs().getMTime();
Payload file = new Payload();
System.out.println("Getting input Stream for " + directory + "/" + filename);
file.setInputStream(channelSftp.get(directory + "/" + filename));
file.setFilename(filename);
file.setLastModified(lastmodified);
files.add(file);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
catch (SftpException e) {
}
return files;
}}
Payload.java
public class Payload {
private String filename;
private InputStream inputStream;
private Date lastModified;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}}
JSch is not thread-safe. Even if it were, there's hardly any performance advantage in using parallel downloads over a single SSH session. It would be as slow as serial downloads. Moreover, you may hit server-side limit of concurrent file handles.
You should open a separate session for each thread/download.
I am struggling to find a good example on how to read and write data in my android app using GSON. Could someone please show me or point me to a good example? I am using this for data persistence between activities.
My professor gave this example to for writing:
Vector v = new Vector(10.0f, 20.0f);
Gson gson = new Gson();
String s = gson.toJson(v);
How would I go about saving that to a file?
How to save your JSON into a file on internal storage:
String filename = "myfile.txt";
Vector v = new Vector(10.0f, 20.0f);
Gson gson = new Gson();
String s = gson.toJson(v);
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(s.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
How to read it back:
FileInputStream fis = context.openFileInput("myfile.txt", Context.MODE_PRIVATE);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
String json = sb.toString();
Gson gson = new Gson();
Vector v = gson.fromJson(json, Vector.class);
Simple Gson example:
public class Main {
public class Power {
private String name;
private Long damage;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getDamage() {
return damage;
}
public void setDamage(Long damage) {
this.damage = damage;
}
public Power() {
super();
}
public Power(String name, Long damage) {
super();
this.name = name;
this.damage = damage;
}
#Override
public String toString() {
return "Power [name=" + name + ", damage=" + damage + "]";
}
}
public class Warrior {
private String name;
private Power power;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Power getPower() {
return power;
}
public void setPower(Power power) {
this.power = power;
}
public Warrior() {
super();
}
public Warrior(String name, Power power) {
super();
this.name = name;
this.power = power;
}
#Override
public String toString() {
return "Warrior [name=" + name + ", power=" + power.toString() + "]";
}
}
public static void main(String[] args) {
Main m = new Main();
m.run();
}
private void run() {
Warrior jake = new Warrior("Jake the dog", new Power("Rubber hand", 123l));
String jsonJake = new Gson().toJson(jake);
System.out.println("Json:"+jsonJake);
Warrior returnToWarrior = new Gson().fromJson(jsonJake, Warrior.class);
System.out.println("Object:"+returnToWarrior.toString());
}
}
Anyways checkout the documentation.
And to persist something in your application you can start with something simple like ORMlite.
Hope this help! :]
UPDATE:
If you really want write the json in a file:
File myFile = new File("/sdcard/myjsonstuff.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(myJsonString);
myOutWriter.close();
fOut.close();
And if you want to read:
File myFile = new File("/sdcard/myjsonstuff.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = ""; //Holds the text
while ((aDataRow = myReader.readLine()) != null)
{
aBuffer += aDataRow ;
}
myReader.close();
Also add: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to your manifest.
But, seriously is so much better use a ORM and store the records in the db. I don't know why you need save the json data in a file, but if I was you, I will use the ORM way.
Maybe in more recent version, but toJson accepts writer that directly writes to file.
ex.:
Vector v = new Vector(10.0f, 20.0f);
Gson gson = new GsonBuilder().create();
Writer writerJ = new FileWriter("keep.json");
gson.toJson(v,writerJ);
Save your class in SharedPrefrences using
public static void saveYourClassInSharedPref(ClassToSave ClassToSave) {
try{
String json = "";
if(ClassToSave != null){
json = new Gson().toJson(ClassToSave);
}
SharedPref.save(KeysSharedPrefs.ClassToSave, json);
}catch (Exception ex){
ex.printStackTrace();
}
}
public static ClassToSave readYourClassFromSharedPref() {
ClassToSave ClassToSave;
try{
String json = SharedPref.read(KeysSharedPrefs.ClassToSave, "");
if(!json.isEmpty()){
ClassToSave = new Gson().fromJson(json, ClassToSave.class);
return ClassToSave;
}
}catch (Exception ex){
ex.printStackTrace();
}
return null;
}
where SharedPref.java
public class SharedPref {
public static String read(String valueKey, String valueDefault) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(App.context);
return prefs.getString(valueKey, valueDefault);
}
public static void save(String valueKey, String value) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(App.context);
SharedPreferences.Editor edit = prefs.edit();
edit.putString(valueKey, value);
edit.commit();
}
}
You can also do this entirely with streams and avoid an intermediate object:
Vector v;
// This should be reused, so private static final
Gson gson = new GsonBuilder().create();
// Read from file:
try (InputStream fileIn = context.openFileInput("myfile.txt", Context.MODE_PRIVATE);
BufferedInputStream bufferedIn = new BufferedInputStream(fileIn, 65536);
Reader reader = new InputStreamReader(bufferedIn, StandardCharsets.UTF_8)) {
gson.fromJson(reader, Vector.class);
}
v = new Vector(10.0f, 20.0f);
// Write to file
try (OutputStream fileOut = context.openFileOutput(filename, Context.MODE_PRIVATE);
OutputStream bufferedOut = new BufferedOutputStream(fileOut, 65536);
Writer writer = new OutputStreamWriter(bufferedOut)) {
gson.toJson(v, writer);
}
Choose buffer sizes appropriately. 64k is flash-friendly, but silly if you only have 1k of data. try-with-resources might also not be supported by some versions of Android.