When I launch the JAR file that I build, JTable does not display UTF-8. When I launch it inside IntelliJ IDEA, it does display correctly.
I have a couple of ideas but cannot find a way to debug it. First of all, the table data is being serialised, maybe there is something I don't know about it and I need to specify somewhere that it is UTF-8?
Secondly, maybe I need to specify somewhere the encoding where I create and populate the JTable as GUI element? I am adding code pieces for both
The code that I use for saving and retrieving data is here:
private void deserialiseStatsData(){
try {
FileInputStream fis = new FileInputStream("tabledata.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
tableData = (TableData) ois.readObject();
fis.close();
ois.close();
} catch (Exception e) {
tableData = new TableData();
}
}
private void serialiseStatsData(){
try {
FileOutputStream fos = new FileOutputStream("tabledata.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(tableData);
oos.close();
fos.close();
}
catch (Exception e) {e.printStackTrace();}
}
Code for creating and populating the table:
private void createUIComponents() {
String headers[] = {"Exercise", "Did Succeed?", "Times Failed Before 1st Success",
"Accuracy (%), ", "Checked Result Before Succeeding"};
TableData dataTable = null;
try {
FileInputStream fis = new FileInputStream("tabledata.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
dataTable = (TableData) ois.readObject();
fis.close();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
Object[][] data;
int rows = dataTable.getRows();
int cols = headers.length;
data = new Object[rows][cols];
for (int j = 0; j < rows; j++) {
data[j][0] = dataTable.getLine(j).getExercise();
data[j][1] = dataTable.getLine(j).isSuccess();
data[j][2] = dataTable.getLine(j).getNoOfFails();
data[j][3] = dataTable.getLine(j).getPercentage();
data[j][4] = dataTable.getLine(j).isAnswerCheckBeforeSuccess();
}
table = new JTable(data, headers);
}
What I have tried:
Added lines to VM Options:
-Dconsole.encoding=UTF-8
-Dfile.encoding=UTF-8
Changed encoding in Settings -> File Encodings to UTF-8
At this point, I don't know what else I could do.
Edited:
I get stuff like this in JTable:
When I should get stuff like this:
Char list which does not display:
union = '\u222A';
intersection = '\u2229';
product = '\u2A2F';
difference = '\u2216';
infinity = '\u221E';
belongsTo = '\u2208';
weakSubset = '\u2286';
properSubset = '\u2282';
Related
I have a Hashmap as a source of data and I'm generating a separate pdf for each key. But when the hashmap length is greater than 2 I'm getting only the 2nd pdf. 2nd one overrides the 1st pdf.(I'm storing HTML in the body key as you can see in the code). I don't want to create separate HTML files and store them in sever.Is there any way where I can store the HTML and generate separate pdf for all keys in hashmap
public byte[] BulkPdf(Map jsonObject) throws ApplicationException, IOException {
LinkedHashMap<String, List<Map<String, Object>>> hashMapDept = new LinkedHashMap<>();
byte[] reportByte = null;
if (!hashMapDept.isEmpty()) {
Integer count = 0;
for (Entry<String, List<Map<String, Object>>> entry : hashMapDept.
entrySet()) {
String body = "";
Writer out = new StringWriter();
Configuration cfg = new Configuration();
try {
cfg.setObjectWrapper(new DefaultObjectWrapper());
String templateStr = UUID.randomUUID().
toString().
replaceAll("-",
"");
logger.debug("templatename --> ",
templateStr);
freemarker.template.Template freemarkerTemplate = new freemarker.template.Template(
templateStr,
new StringReader(html),
cfg);
freemarkerTemplate.process(jsonObject,
out);
body = out.toString();
} catch (TemplateException | IOException | ApplicationException e) {
logger.debug("template pdf exception --> ",
e.getMessage());
out.flush();
e.printStackTrace();
cfg.clearTemplateCache();
} finally {
out.flush();
cfg.clearTemplateCache();
}
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.withHtmlContent(body,
"pathforpdf");
builder.useFastMode();
builder.toStream(outputStream);
builder.run();
reportByte = outputStream.toByteArray();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return reportByte;
}
My application streams twitter data and writes them to files.
while(true){
Status status = queue.poll();
if (status == null) {
Thread.sleep(100);
}
if(status!=null){
list.add(status);
}
if(list.size()==10){
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
String uuid = UUID.randomUUID().toString();
String filename = "C:/path/"+topic+"-"+uuid+".ser";
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(list);
tweetsDownloaded += list.size();
if(tweetsDownloaded % 100==0)
System.out.println(tweetsDownloaded+" tweets downloaded");
// System.out.println("File: "+filename+" written.");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
list.clear();
}
I have this code which gets data from files.
while(true){
File[] files = folder.listFiles();
if(files != null){
Arrays.sort(//sorting...);
//Here we manage each single file, from data-load until the deletion
for(int i = 0; i<files.length; i++){
loadTweets(files[i].getAbsolutePath());
//TODO manageStatuses
files[i].delete();
statusList.clear();
}
}
}
The method loadTweets() does the following operations:
private static void loadTweets(String filename) {
FileInputStream fis = null;
ObjectInputStream in = null;
try{
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
statusList = (List<Status>) in.readObject();
in.close();
}
catch(IOException | ClassNotFoundException ex){
ex.printStackTrace();
}
}
Unfortunately, I don't know why sometimes it throws a
EOFException
when running this line
statusList = (List<Status>) in.readObject();
Anybody knows how I can solve this? Thank you.
I've seen that you're passing the file correctly with the getAbsolutePath() based on a previous question of yours
From what I've read that can be a couple of things, one of them the file being null.
Explaining this idea, you might have written the file but something caused the file to have nothing inside, this might cause an EOFException. The file in fact exists it's just empty
EDIT
Try to enclose the code in while(in.available() > 0)
It would look like this
private static void loadTweets(String filename) {
FileInputStream fis = null;
ObjectInputStream in = null;
try{
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
while(in.available() > 0) {
statusList = (List<Status>) in.readObject();
}
in.close();
}
catch(IOException | ClassNotFoundException ex){
ex.printStackTrace();
}
}
Found out what was necessary to solve this. Thanks to #VGR's comment, I thought to pause the executing thread for 0.2 seconds if the file has been created less than a second ago.
if(System.currentTimeMillis()-files[i].lastModified()<1000){
Thread.sleep(200);
This prevents the exception and the application works now fine.
I'm attempting to merge multiple byte arrays to a single PDF and have that working, but it seems that the file grows larger and larger when it should just replace the file. It also seems that the file is not closing correctly. I don't know if I am missing a list in the merge logic, but that's the only place I could think it would be.
public class MergePDF {
private static final Logger LOGGER = Logger.getLogger(MergePDF.class);
private static ByteArrayOutputStream baos = new ByteArrayOutputStream();
public static byte[] mergePDF (List<byte[]> pdfList) {
try {
Document PDFCombo = new Document();
PdfSmartCopy copyCombo = new PdfSmartCopy(PDFCombo, baos);
PDFCombo.open();
PdfReader readInputPdf = null;
int num_of_pages = 0;
for (int i = 0; i < pdfList.size(); i++) {
readInputPdf = new PdfReader(pdfList.get(i));
num_of_pages = readInputPdf.getNumberOfPages();
for (int page = 0 ; page < num_of_pages;) {
copyCombo.addPage(copyCombo.getImportedPage(readInputPdf, ++page));
}
}
PDFCombo.close();
} catch (Exception e) {
LOGGER.error(e);
}
return baos.toByteArray();
}
}
I assume that I'm missing some sort of close in the process because when I save the file at a later time, it seems to tack on the size, but the PDF that I view doesn't add any additional pages.
Here is how I am saving the PDF off before sending it to a third party. When sent it is a byte array.
try {
FileOutputStream out = new FileOutputStream(outMessage.getDocumentTitle());
out.write(outMessage.getPayload());
out.close();
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
I have been told that there are multiple PDF Headers and EOF's in the bytearray that I'm sending over.
Based on #mkl's comment, it turns out that this was indeed true:
#mkl's suggestion in combination with your mention of the "close"
issue could indeed indicate that you're not replacing one set of bytes
by another set of bytes, but that you are, in fact, adding a new set
of bytes to the old set of bytes.
This is how to solve the problem:
public class MergePDF {
private static final Logger LOGGER = Logger.getLogger(MergePDF.class);
public static byte[] mergePDF (List<byte[]> pdfList) {
try {
Document PDFCombo = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfSmartCopy copyCombo = new PdfSmartCopy(PDFCombo, baos);
PDFCombo.open();
PdfReader readInputPdf = null;
int num_of_pages = 0;
for (int i = 0; i < pdfList.size(); i++) {
readInputPdf = new PdfReader(pdfList.get(i));
num_of_pages = readInputPdf.getNumberOfPages();
for (int page = 0 ; page < num_of_pages;) {
copyCombo.addPage(copyCombo.getImportedPage(readInputPdf, ++page));
}
}
PDFCombo.close();
} catch (Exception e) {
LOGGER.error(e);
}
return baos.toByteArray();
}
}
Now you probably understand why the person teaching you how to code explained that using static variables is a bad idea in most cases.
So what I am trying to do here is load a Customer object in from a file but I don't know how to return the object in the method. As the code stands now I get an error saying return type incompatible java.lang.object found needs Customer.
public static Customer loadCustomer(String customerNum) {
try {
String fileName = customerNum + ".txt";
InputStream file = new FileInputStream(fileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
Object x = input.readObject();
return x;
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
I was thinking I could do something like this but it doesn't work either.
public static Customer loadCustomer(String customerNum) {
try {
String fileName = customerNum + ".txt";
InputStream file = new FileInputStream(fileName);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
Object x = input.readObject();
Customer y = new Customer(x);
return y;
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
//or do something like this:Customer x = new Customer(input.readObject)
Im still in the java learning process so if you see any other errors please let me know. As always I appreciate everyones time for helping me out with this, looking forward to the day when I have the knowledge to pay it forward and help others.
Try replacing Object x = input.readObject(); with Customer x = (Customer) input.readObject();
I have a question regarding internal files in android.. I tried to write some data into a file and then read it back however, it seems like I can't write data to a file unless I cast it to an integer first.. is there anyway that I can save double or float values.. I added the code I'm trying to use below:
FormatCluster formatCluster = ((FormatCluster)objectCluster.returnFormatCluster(ofFormats,"Calibrated"));
if (formatCluster != null) {
//Obtain data for text view
calibratedDataArray[0] = formatCluster.mData;
calibratedUnits = formatCluster.mUnits;
A.setText("data: " + formatCluster.mData);
String filename = "myfile";
//String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write((int)formatCluster.mData);//here I don't want to cast the value to integer
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
//testing.setText)
double ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis;
try {
fis = context.openFileInput( filename );
try {
while( (ch = fis.read()) != -1)
testing.setText(fileContent.append(ch));
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Envelope your InputStream and OutputStream with a DataInputStream and a DataOutputStream. These classes have the method you need