How to parse a JSONString, from a once JSONString.stringify simple array that now "appears flattened" inside, and turn its values back into a Java List or Java Array? (Using Jersey 1.x & Java) ? Array originally started as [1,2,3] before it was stringify-ed.
items = (3) [" To", "8357", "30028"] --> JSON.stringify(items) sent through rest call
Chrome Dev Tools's Request Payload after rest call:
items=%5B%22%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0To%22%2C%228357%22%2C%2230028%22%5D
/*inside (Jersey) Rest Resource
#POST
#Path("/...")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response receive(#Context SecurityContext securityContext, #Context
HttpServletRequest srequest, String jsonString) throws URISyntaxException,
JSONException ...
/*eclipse watch on jsonString inside (Jersey) Rest Resource
items=%5B%22%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0To%22%2C%228357%22%2C%2230028%22%5D
*/[enter image description here][2]
NOTE: There is no name value. There is no entity.
There's only a very simple string of IDs because that's all I need. (Is that supported by Jersey 1.X or JAX-RS 1.X?)
JSONArray jSONArray = new JSONArray(java.util.Arrays.asList(jsonString));
Eclipse jSONArray Expression: jSONArray
--myArrayList
----elementData
------[0] "items=%5B%22%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0To%22%2C%228357%22%2C%2230028%22%5D"
----------value
------------[0..99]
---------------[0] i
---------------1 t
---------------[2] e
---------------[3] m
---------------[4] s
---------------[5] =
---------------[6] %
---------------[7] 5
---------------[8] B ....
I cannot understand exactly your original question, but one of the way is:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFileChooser;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonParser {
JFileChooser chooser = new JFileChooser();
File f;
static String fn = "";
static String js1 = "{\"name\": \"LALA\", \"email\": \"tst#tst.com\"}";
String name = "name";
String email = "email";
String fName = "firsName";
String city = "city";
// ... other needed fields
User u1 = null;
public JsonParser() {
parseFile();
System.out.println("\n" + u1.toShortString());
}
private String openFchooser() throws FileNotFoundException, IOException, InterruptedException, Exception {
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
f = chooser.getSelectedFile();
}
return f.getAbsolutePath();
}
// To parse JSON files with data
//===========================================
public void parseFile() {
JSONParser parser = new JSONParser();
try {
// To parse obj 1
Object obj1 = parser.parse(js1);
System.out.println("User 1: " + obj1.toString());
System.out.println();
JSONObject jobj1 = (JSONObject) obj1;
String from_name = jobj1.get(name).toString();
String from_email = jobj1.get(email).toString();
// String from_fName = jobj1.get(fName).toString();
// String from_city = jobj1.get(city).toString();
u1 = new User(from_name, from_email, null, null);
// System.out.println(u1.toString() + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new JsonParser();
}
class User {
String name = null;
String email = null;
String fName = null;
String city = null;
public User(String n, String e, String f, String c) {
this.name = n;
this.email = e;
this.fName = f;
this.city = c;
}
public String getFirsName() {
return this.name;
}
public String setFirsName(String s) {
return this.name = s;
}
public String getEmail() {
return this.email;
}
public String setEmail(String s) {
return this.email = s;
}
public String toString() {
return "{\"name\":" + this.name + ", "
+ "\"email\":" + this.email + ", "
+ "\"firsName\":" + this.fName + ", "
+ "\"city\":" + this.city + "\"}";
}
public String toShortString() {
return "{\"name\": \"" + this.name + "\", "
+ "\"email\": \"" + this.email + "\"}";
}
};
}
OUTPUT:
User 1: {"name":"LALA","email":"tst#tst.com"}
{"name": "LALA", "email": "tst#tst.com"}
Thanks guys. I managed to find an alternative send & receive:
now sending array without stringify-ing it first
receiving with:
public Response archiveSelectedApplicants(#Context SecurityContext securityContext, #Context HttpServletRequest srequest,
#FormParam("items[]") List items) throws URISyntaxException
Related
I created API using spring boot to upload the CSV file using rest controller, I want to import the data into MySQL table while upload the csv to the server.
I have mysql table called attendee as like below
id | event_id | name | email
User want to upload csv file from client app (angular 2) to server and need to import data into attendee table.
CSV will be like this
name | email
John , Doe
So I created REST API events/<event_id>/attendee
#PostMapping(value = "/{id}/attendee")
public ResponseEntity<String> uploadAttendee(#PathVariable Integer id,#RequestParam("file") MultipartFile file) {
String message = "";
try {
storageService.store(file);
files.add(file.getOriginalFilename());
message = "You successfully uploaded " + file.getOriginalFilename() + "!";
// Here I am to import into database
return ResponseEntity.status(HttpStatus.OK).body(message);
} catch (Exception e) {
message = "FAIL to upload " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
}
}
Can someone so me full Example of importing into database. I'm not much experienced in java spring framework. It will useful someone explain in detail.
You can use jackson dataformat library for csv parsing.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>2.5.3</version>
</dependency>
And for code, you can do like:
CsvSchema bootstrapSchema = CsvSchema.emptySchema().withHeader();
CsvMapper mapper = new CsvMapper();
MappingIterator<YourDto> readValues = mapper.readerFor(type).with(bootstrapSchema).readValues(file);
List<YourDto> allValues= readValues.readAll();
After you have list of values, you can save it in mysql.
Dto will contain all the fields available in csv, for ex.
class YourDto{
String name;
String email;
public YourDto() {
super();
}
public YourDto(String name, String email) {
super();
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
csv will look like:
name,email
John Doe, johndoe#gmail.com
Mark Page, markpage#gmail.com
#PostMapping(value = "/devices/upload", produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<Map<String, String>> handleFileUpload(#RequestParam("file") MultipartFile file)
throws IOException {
LOGGER.info("DeviceController:handleFileUpload start");
String refId = String.valueOf(System.currentTimeMillis());
String fileName = file.getOriginalFilename();
Map<String, String> result = new HashMap<>();
result.put("refId", refId);
if (file.isEmpty()) {
result.put("msg", "Empty File: " + fileName);
return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
}
try (InputStream inStream = file.getInputStream()) {
List<String> lines = IOUtils.readLines(inStream, "UTF-8");
ExecutorService service = DMResourceManager.getExecutorService();
service.submit(() -> {
try {
deviceRegisterService.register(refId, fileName, lines);
} catch (FileNotFoundException | SQLException e) {
LOGGER.error("Error while calling deviceRegisterService's register method ", e);
}
});
result.put("msg", "Submitted File: " + fileName);
LOGGER.info("DeviceController:handleFileUpload end");
return new ResponseEntity<>(result, HttpStatus.OK);
}
}
public void register(String refId, String originalFileName, List<String> lines)
throws SQLException, FileNotFoundException {
LOGGER.info("DeviceRegisterService:register");
deviceRepository.uploadDevice(refId, originalFileName, lines);
}
public void uploadDevice(String refId, String originalFileName, List<String> lines) throws DataAccessException {
String sql = "INSERT INTO device_registration(Device_Id, Device_Name, Serial_Number, Device_Description, Device_Type, Manufacturer_Name, Manufactured_Date, Device_IMEI , Sim_Number , Sim_Type, Battery_Type, Hardware_Version, Base_Firmware_Version, Firmware_Filename, Config_Version, Config_Filename, Device_Mac_Address, Device_RFID_Info, RFID_Version, RFID_Filename, Status)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
for (int i = 1; i < lines.size() - 1; i++) {
String[] arrOfStr = lines.get(i).split(",");
for (int j = 0; j < arrOfStr.length; j = +arrOfStr.length) {
jdbcTemplate.update(sql, UUID.randomUUID().toString(), arrOfStr[0], arrOfStr[1], arrOfStr[2],
arrOfStr[3], arrOfStr[4], arrOfStr[5], arrOfStr[6], arrOfStr[7], arrOfStr[8], arrOfStr[9],
arrOfStr[10], arrOfStr[11], arrOfStr[12], arrOfStr[13], arrOfStr[14], arrOfStr[15],
arrOfStr[16], arrOfStr[17], arrOfStr[18], arrOfStr[19]);
}
}
LOGGER.info("reference Id generated after inserting " + originalFileName + " + file in db:" + refId);
}
#Component
public class DMResourceManager {
private final static Logger LOGGER = LoggerFactory.getLogger(DMResourceManager.class);
private final static ListeningExecutorService executorService =
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10,
new ThreadFactoryBuilder().setNameFormat("dm-api-pool-%d").build()));
private DMResourceManager() {
}
public static ListeningExecutorService getExecutorService() {
return (executorService);
}
#PreDestroy
public void destroy() {
LOGGER.info("Attempting ExecutorService.shutdown()...");
executorService.shutdown();
try {
if (!executorService.awaitTermination(3, TimeUnit.SECONDS)) {
LOGGER.info("ExecutorService.shutdownNow() issued.");
executorService.shutdownNow();
if (!executorService.awaitTermination(3, TimeUnit.SECONDS)) {
LOGGER.warn("ExecutorService failed to shutdownNow() in 15 seconds.");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
executorService.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
LOGGER.warn("ExecutorService interrupted during shutdown.", ie);
}
LOGGER.info("ExecutorService.shutdown() complete.");
}`enter code here`
}
This is a simple example where I'm trying to write and read Objects stored in ArrayList to/from file.
Writing file is working. Reading file is working only for first Object in my ArrayList. How should I make this into a loop?
I tried with something like:
`while(ois !=null) {
Person result = (Person) ois.readObject();
persons.add(result);
}
but it's not working.
Here is full test code:
public class Data {
static ArrayList<Person> persons = new ArrayList<Person>();
public static void savePersons() throws IOException{
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object for examle */
for(int i = 0; i<5; i++){
Person personTest = new Person("name", "surname", "email", "1234567890");
persons.add(personTest);
}
try{
fout = new FileOutputStream("C:\\data.dat", 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");
} finally {
if(oos != null){
oos.close();
}
}
}
public static void loadPersons() throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
/** Clean 'persons' array for TEST of load data*/
persons.removeAll(persons);
try {
fis = new FileInputStream("C:\\data.dat");
ois = new ObjectInputStream(fis);
Person result = (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");
} finally {
if(ois != null){
ois .close();
}
}
}
}
Person class:
public class Person implements Serializable {
private String name;
private String surname;
private String mail;
private String telephone;
Person person;
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;
}}
Main class:
public class Test {
public static void main(String[] args) {
Data.savePersons();
Data.loadPersons();
}}
Here you go... please take note of the following:
YES, Chetan Jadhav CD's suggestion WORKS. B
Use an IDE like Eclipse to help you debug your code and make your life easier.
Be clear about what your error is (show stack trace, etc..) Note the modification to your catch clause that prints:
System.out.println("Saving ERROR: " + ex.getMessage());
Put all your code in one file before you ask for help to make everyone's life easier.
Make each 'Person' at least someone unique by numbering them with your index Use .ser for a serializable file, rather than .dat
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Data {
private static final String SER_FILE = "C:\\view\\data.ser";
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons();
Data.loadPersons();
}
public static void savePersons() throws IOException {
/** Make 5 'Person' object for example */
for (int i = 0; i < 5; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890-" +i);
persons.add(personTest);
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SER_FILE, true));) {
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());
}
}
public static void loadPersons() throws IOException {
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SER_FILE));){
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");
persons.stream().forEach(System.out::println);
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
}
}
}
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;
}
#Override
public String toString() {
return "Person [name=" + name + ", surname=" + surname + ", mail=" + mail + ", telephone=" + telephone + "]";
}
}
I am trying to get some weather information from Yahoo APIs. This is my JSON:
JSON
This is my DTO:
public class forecast implements Serializable {
private static final long serialVersionUID = -520652416977871134L;
private String text;
private String high;
private String day;
private String code;
private String low;
private String date;
public forecast() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getHigh() {
return high;
}
public void setHigh(String high) {
this.high = high;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getLow() {
return low;
}
public void setLow(String low) {
this.low = low;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return "ClassPojo [text = " + text + ", high = " + high + ", day = "
+ day + ", code = " + code + ", low = " + low + ", date = "
+ date + "]";
}
}
I am only interested for the forecast element.
When I try to read the data de-serialized into my DTO all of them are null. I sense that I have not formatted my DTO properly.
Also, what Is the right way to map JSON to POJOs?
EDIT: this is my code for deserializing
String endpoint = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20"
+ "where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Rhodes%2C%20Gr%22)&"
+ "format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
try {
URL endpointURL = new URL(endpoint);
HttpURLConnection connection = (HttpURLConnection) endpointURL
.openConnection();
connection.connect();
InputStream input = connection.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(input));
reader.setLenient(true);
forecast response = new Gson().fromJson(reader,
forecast.class);
Log.d("forecast", response.toString());//override toString() to return all the values of the object
} catch (IOException e) {
e.printStackTrace();
}
Your JSON (which you get from Yahoo) is very complex. So it can not be easily mapped to simple POJO (but you still can write huge POJO that contains fields for all corresponding nested JSON elements).
But it is possible to parse and extract specific elements from JSON.
The code:
public static void main(String[] args) {
String endpoint = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20"
+ "where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Rhodes%2C%20Gr%22)&"
+ "format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
try {
URL endpointURL = new URL(endpoint);
HttpURLConnection connection = (HttpURLConnection) endpointURL
.openConnection();
connection.connect();
InputStream input = connection.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(input));
reader.setLenient(true);
JsonElement forecastSubObject = new JsonParser().parse(reader).
getAsJsonObject().get("query").
getAsJsonObject().get("results").
getAsJsonObject().get("channel").
getAsJsonObject().get("item").
getAsJsonObject().get("forecast");
System.out.println(forecastSubObject.toString());
List<forecast> forecasts = (List<forecast>)new Gson().fromJson(forecastSubObject, List.class);
System.out.println("forecast : " + forecasts);
System.out.println("first forecast: " + forecasts.get(0));
} catch (IOException e) {
e.printStackTrace();
}
}
Using JsonParser you can walk through elements (by theirs names). When 'forecast' element is reached corresponding string is extracted. Then it parsed as usual object and mapped to list of your forecast POJO.
Generally speaking mapping to/from JSON is very wide sphere. Different libraries provide different ways for achieving this (from simple and dirty to complex but reliable).
I want to get the data of a database table to the client end. I'm sending the data via a JSON. When I print the output result in the client end it gives the following result.
{"pricing":null}
When I print return statement in the server end, it outputs the following
[Connection.Pricing#3d5bae2]
There are no errors. What have I done wrong?
Here is my Client Side Code
public String loadTable(String tablename) throws ClientProtocolException, IOException {
pathParams.add("tablename", tablename);
ClientResponse response = service.path("access").path("loadtable").queryParams(pathParams).type(MediaType.APPLICATION_JSON).get(ClientResponse.class);
String responseString = response.getEntity(String.class);
return responseString;
This is my Server End
#Path("/loadtable")
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Pricing> loadTable(#QueryParam("tablename") String tablename) throws Exception {
List<Pricing> pricing = new ArrayList<Pricing>();
try {
query = c.prepareStatement("select * from " + tablename);
ResultSet ets_rs = query.executeQuery();
while (ets_rs.next()) {
pricing.add(new Pricing(ets_rs.getString(1), ets_rs.getString(2), ets_rs.getString(3), ets_rs.getString(4), ets_rs.getString(5), ets_rs.getString(6)));
}
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null) {
c.close();
}
}
return pricing;
Here is my POJO class in the server end
#XmlRootElement
class Pricing {
String category;
String lower_limit;
String class_no;
String value;
String employee;
String upper_limit;
public Pricing() {
}
Pricing(String a, String b, String c, String d, String e, String f) {
category = a;
lower_limit = b;
upper_limit = c;
class_no = d;
value = e;
employee = f;
}
//getters
}
You need to override toString method in your Pricing class to print the object in a beautiful way. The default toString() method shows the object class and its hash code separated by # character and hence you see this
Pricing#3d5bae2
Here is one implmentation of toString method for Pricing class:
#Override
public String toString() {
return "Pricing [category=" + category + ", lower_limit=" + lower_limit
+ ", class_no=" + class_no + ", value=" + value + ", employee="
+ employee + ", upper_limit=" + upper_limit + "]";
}
I'm having major trouble piecing this together. I have basic read and write functionality. What I need is for the input from file 'Books.txt' to be checked so that:
ISBN is valid
CopyNumber, Year and Statistics should be numeric
Title, Author and Publisher must contain values
BorrowDate must be a valid date
ReturnDate if available must be a valid date
LibraryCardNumber if available must be numeric.
If a book is not borrowed the two last fields are nonexistent.
2 sample rows from 'Books.txt':
9780140455168#2#The Twelve Caesars#Suetonius#Penguin Classics#2007#3#101009#101030#5478
9780141188607#1#Claudius the God#Robert Graves#Penguin Classics#2006#2#080123
Error lines should be written to 'ErrorLines.txt' with an error-message, e.g. Wrong ISBN. Error-free books should be written to 'NewBooks.txt' sorted by name of author.
Here's what I've got so far. I'm not looking for a complete solution, because I obviously have a looong way to go, but if someone would be so kind as to give me some pointers, I'd be extremely grateful! And yes, it's homework :D
Do I need to make a try loop to validate the input...?
The Library class:
import java.util.ArrayList;
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Library {
public void readFromFile (String filename) throws IOException {
String inLine;
File inFile;
inFile = new File("Books.txt");
BufferedReader fIn = new BufferedReader(new FileReader(inFile));
inLine = fIn.readLine();
while (inLine != null) {
inLine = fIn.readLine();
aBookList.add(inLine + "\n");
}
fIn.close();
}
public void writeToFile (String fileName) throws IOException {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(fileName));
bw.write("???"); //Dont know what to put here...
bw.newLine();
} catch (IOException e) {
System.out.println("Error writing file.");
} finally {
bw.close();
}
}
public static boolean isISBN13Valid(isbn) {
int check = 0;
for (int i = 0; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1));
}
for (int i = 1; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1)) * 3;
}
check += Integer.valueOf(isbn.substring(12));
return check % 10 == 0;
}
}
And here's the Book class:
import java.util.*;
import java.io.*;
public class Book {
Book b = new Book();
private static ArrayList<String> aBookList = new ArrayList<String>();
private String Isbn;
private int CopyNumber;
private String Title;
private String Author;
private String Publisher;
private int Year;
private int Statistics;
private String BorrowDate;
private String ReturnDate;
private int LibraryCardNumber;
public void bookInfo (String nIsbn, int nCopyNumber, String nTitle, String nAuthor, String nPublisher, int nYear,
int nStatistics, String nBorrowDate, String nReturnDate, int nLibraryCardNumber) {
Isbn = nIsbn;
CopyNumber = nCopyNumber;
Title = nTitle;
Author = nAuthor;
Publisher = nPublisher;
Year = nYear;
Statistics = nStatistics;
BorrowDate = nBorrowDate;
ReturnDate = nReturnDate;
LibraryCardNumber = nLibraryCardNumber;
}
public void bookInfo (String Row) {
StringTokenizer sT = new StringTokenizer(Row);
Isbn = sT.nextToken("#");
CopyNumber = Integer.parseInt(sT.nextToken("#") );
Title = sT.nextToken("#");
Author = sT.nextToken("#");
Publisher = sT.nextToken("#");
Year = Integer.parseInt(sT.nextToken("#") );
Statistics = Integer.parseInt(sT.nextToken("#") );
BorrowDate = sT.nextToken("#");
ReturnDate = sT.nextToken("#");
LibraryCardNumber = Integer.parseInt(sT.nextToken("#") );
}
public void setIsbn(String nIsbn) {
Isbn = nIsbn;
}
public void setCopynumber(int nCopyNumber) {
CopyNumber = nCopyNumber;
}
public void setTitle(String nTitle) {
Title = nTitle;
}
public void setAuthor(String nAuthor) {
Author = nAuthor;
}
public void setPublisher(String nPublisher) {
Publisher = nPublisher;
}
public void setYear(int nYear) {
Year = nYear;
}
public void setStatistics(int nStatistics) {
Statistics = nStatistics;
}
public void setBorrowDate(String nBorrowDate) {
BorrowDate = nBorrowDate;
}
public void setReturnDate(String nReturnDate) {
ReturnDate = nReturnDate;
}
public void setLibraryCardNumber(int nLibraryCardNumber) {
LibraryCardNumber = nLibraryCardNumber;
}
public String getAll () {
String s = " ";
return (Isbn + s + CopyNumber + s + Title + s + Author + s + Publisher + s +
Year + s + Statistics + s + BorrowDate + s + ReturnDate + s +
LibraryCardNumber);
}
public void showAll () {
String t = "\t";
System.out.println(Isbn + t + CopyNumber + t + Title + t + Author + t +
Publisher + t + Year + t + Statistics + t +
BorrowDate + t + ReturnDate + t + LibraryCardNumber);
}
}
And finally there's the Main class with main method:
public class Main<aBookList> implements Comparable<aBookList> {
public static void main(String [] args) throws Exception {
new Library().readFromFile("Books.txt");
new Library().writeToFile("NewBooks.txt");
new Library().writeToFile("ErrorLines.txt");
}
#Override
public int compareTo(aBookList o) {
return 0;
}
}
as it is homework, i will point you direction, not give you code
1) you have lot of mess here, ie i'm not sure why you have compare in your main class? instead of creating getAll method in bookInfo(which is named against java nameing convention) just override toString method
2) why do you have list of strings? read a line, convert this into book, if book is valid add it to your list, otherwise report an error
3) move your isISBN13Valid method to book
4) write to file -> loop through your list, and save each element into file by bw.write(book.toString()),
5) create second method createErrorFile, then each error what you will have add into your error list, and after you call that method, you will sace each element into given file, it is not perfetc solution, better will be if you add error to file each time when it occur.
6) create one instance of library in your main method, and just call on it all your method, and avoid using static fields in your project(sometimes you must, but if you don;t need, just avoid them)
7) names for method import/ export i think sounds nicer than read from file read from file