Splitting skips half a content when splitting by # - java

I have an android application that requests data from a text file. when I try to separate the data and initialize classes, I have serious trouble because half the data after splitting is missing. The code for the DataSource is:
indicators = new ArrayList<Indicator>();
try {
InputStream fileStream = getResources().openRawResource(
R.raw.indicators);
int fileLen = fileStream.available();
// Read the entire resource into a local byte buffer.
byte[] fileBuffer = new byte[fileLen];
fileStream.read(fileBuffer);
fileStream.close();
displayText = new String(fileBuffer);
String[] counts = displayText.split("#");
for(String i: counts) {
String[] temps = i.split(";");
indicators.add(new Indicator(temps[0],temps[1],temps[2]));
}
} catch (IOException e) {
// exception handling
}
for(Indicator i: indicators) Log.v("indicator", i.toString());
and the code for the Indicator class can be found here:
public class Indicator {
private String name;
private String isoCode;
private String topic;
public Indicator(String topic, String isoCode,String name) {
this.name = name;
this.isoCode = isoCode;
this.topic = topic;
}
public String getName() {
return this.name;
}
public String getIsoCode() {
return this.isoCode;
}
public String getTopic() {
return this.topic;
}
public String toString() {
return (this.topic + "," + this.isoCode + "," + this.name);
}
}
After doing this process the following log file comes up with a lot of content missing:
http://pastebin.com/1j5s1Z81
The file seems to be skipping every other entry and because of that, my entire software is messing up. The source file below is:
http://pastebin.com/eAzppMdb

I have not been able to solve the issue by ammending the command. I found a way around this problem however by using the BufferedReader class that read the opened string in. This has seemed to solve the issue.

Related

Saving multiple input data in one .txt file. Is it possible to overwrite and get data from specific line?

Code first:
import java.io.*;
import java.util.Scanner;
public class Test {
public String date;
public String fridge1;
public String fridge2;
public String info;
static final int lineNumber = 0;
public Test(String date, String fridge1, String fridge2, String info) {
this.date = date;
this.fridge1 = fridge1;
this.fridge2 = fridge2;
this.info = info;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFridge1() {
return fridge1;
}
public void setFridge1(String fridge1) {
this.fridge1 = fridge1;
}
public String getFridge2() {
return fridge2;
}
public void setFridge2(String fridge2) {
this.fridge2 = fridge2;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
#Override
public String toString() {
return
date + "\n" +
fridge1 + "\n" +
fridge2 + "\n" +
info + "\n";
}
public void saveData() {
File file = new File("text.txt");
boolean checker = true;
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains(date)) {
checker = false;
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (checker) {
try (FileOutputStream fos = new FileOutputStream("text.txt", true)) {
fos.write(toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} else {
...
}
}
}
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
// Test test = new Test("19/02/1992", "10", "9", "ok");
// test.saveData();
Test test2 = new Test("19/02/1900", "8", "4", "not ok");
test2.saveData();
}
}
I want to do program in Java to get some inputs and date, mostly Strings. I just create a methods to write all data in one .txt file, one data - 1 line. If there is already existing date program is not writing new data. Finally, I would like to overwrite data. If I put the same date in, I would like to overwrite existing date to new one. So in my mind if I have in .txt file this data:
line1 17/05/16 line2 blabla line3 blabla line4 blabla
and I will put in Main this:
Test test2 = new Test("17/05/16", "8", "4", "not ok");
test2.saveData();
it should find where is 17/05/16 and then replace lines 2-4 like this.
line1 17/05/16
line2 8
line3 4
line4 not ok
It is possible? Then how to find out all data in reverse way? In mean when I would like to check my data from specific date ex. 17/05/16?
As you can see I just stuck in moment when I have to search where is my data. I can't find good methods.
When your program does start, your first step must always be reading whole text file into memory, line by line. Visit this page how you can achive it. Use your timestamp as key for the HashMap.
One advantage of HashMap is, you can easily check of occurences or add some data at the end. And if you want just update an existing entry, use the same key and the content will be overwritten.
After this, the next page demonstrate how to write the content back to your text file.
Please note: As I wrote in comment section the use of Spring Boot is a better option for your task.

Decode koi8-r string and quoted-printable in java

I got a .eml file, and some attachments inside
one of attachments - is .rar file
I using Tika to extract this rar, but sometimes Tika cant correctly convert some names of files, for example - such a name
=?koi8-r?Q?6=5F=F4=ED=5F15=2E05=2Erar?=
So i was looking for an answer, how to convert such a string to correctly readed value
Is there any libraries in java, to do this?
I guess it happends cause string got =?koi8-r?Q? in the start, so maybe, if i convert string to something like this, i will get move convertable value, like this 6=5F=F4=ED=5F15=2E05=2E, but if i will do so, i finnaly couldnt find a solution to convert
Does anybody know how to convert such a string correctly?
I spend a lot of time to make it, but still - no results...
Here is a code
public class EncodingUtils {
private EncodingUtils() {
}
public static String decodeKoi8r(String text) {
String decode;
try {
decode = MimeUtility.decodeText(text);
} catch (UnsupportedEncodingException e) {
decode = text;
}
if (isQuotedKoi8r(decode)) {
decode = decode(text, "KOI8-R", "quoted-printable", "KOI8-R");
}
return decode;
}
public static boolean isQuotedKoi8r(String text) {
return text.contains("=") || text.toLowerCase().contains("koi8-r");
}
public static String decode(String text, String textEncoding, String encoding, String resultCharset) {
if (text.length() == 0) {
return text;
}
try {
byte[] bytes = text.getBytes(textEncoding);
InputStream decodedStream = MimeUtility.decode(new ByteArrayInputStream(bytes), encoding);
byte[] tmp = new byte[bytes.length];
int n = decodedStream.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return new String(res, resultCharset);
} catch (IOException | MessagingException e) {
return text;
}
}
}
And test:
public class EncodingUtilsTest {
#Test
public void koi8r() {
String input = "=?koi8-r?Q?11=5F=F4=ED=5F21=2E05=2Erar?=";
String decode = EncodingUtils.decodeKoi8r(input);
Assertions.assertEquals("11_ТМ_21.05.rar", decode);
}
#Test
public void koi8rWithoutStartTag() {
String input = "=CF=D4=C4=C5=CC=D8=CE=D9=CD =D4=D2=C1=CE=DB=C5=CD =D2=C5=DA=C0=CD=.eml";
String decode = EncodingUtils.decodeKoi8r(input);
Assertions.assertEquals("отдельным траншем резюм=.eml", decode);
}
}
Good day!

Separating Parsing Method

I'm creating a program which handles SKU's. I currently have two classes in my program, the SKU class is the main class and a Store class in which an ArrayList is initialised and SKU objects are stored in the array. I currently have a method in my SKU class which takes input from a file, parses the data and stores the data using a String tokenizer in the objects variables and adds the objects to the array in the Store class. The problem I'm facing is that I'm wanting to separate the parsing method in the SKU class so that it simply reads from a line, and then have a separate method which takes a file input for the parser and finally update my Store class so that it initialises the products with the parsed data. Please, can you help me in regards to this?
My parsing method in the SKU class is currently as follows:
public void parser() {
try {
// create a Buffered Reader object instance with a FileReader
BufferedReader br = new BufferedReader(new FileReader("products.txt"));
// read from first line from the text file
String fileRead = br.readLine();
// skip first line from sample file as it contains headings
int lineNumber = 0;
// loop until all lines are read
while (fileRead != null)
{
if(lineNumber == 0) {
lineNumber++;
continue;
}
lineNumber++;
// use string.split to load a string array with the values from each line of
// the file, using a tab as the delimiter
String[] tokenize = fileRead.split("\t");
// assume file is made correctly
// and make temporary variables for the three types of data
String tempProductCode = tokenize[0];
String tempDescription = tokenize[1];
BigDecimal tempPrice = new BigDecimal(tokenize[2]);
// create temporary instance of SKU object
// and load with three data values
SKU tempObj = new SKU();
tempObj.setProductCode(tempProductCode);
tempObj.setDescription(tempDescription);
tempObj.setPrice(tempPrice);
// add to array list
Store.mySkuArrayList.add(tempObj);
// read next line before looping
// if end of file reached
fileRead = br.readLine();
}
// close file stream
br.close();
}
// handle exceptions
catch (FileNotFoundException fnfe)
{
System.out.println("file not found");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
My Store class is as follows:
public class Store {
public static ArrayList<SKU> mySkuArrayList = new ArrayList<SKU>();
public void addSKU(SKU sku) {
mySkuArrayList.add(sku);
}
Split your code to three separate classes. SkuFile class represents text file where sku codes is stored, this class knows how to every sku entry stored and able to parse it. Sku class contains data. Store class contains
list of Sku and accept SkuFile in it's constructor.
class SkuFile {
private String path;
SkuFile(String path) {
this.path = path;
}
List<Sku> readAllSku() {
ArrayList<Sku> result = new ArrayList<>();
try {
List<String> lines = Files.readAllLines(new File(path).toPath());
for(String skuLine : lines) {
result.add(parseFrom(skuLine));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
private Sku parseFrom(String data){
String[] tokenize = data.split("\t");
productCode = tokenize[0];
description = tokenize[1];
price = new BigDecimal(tokenize[2]);
return new Sku(productCode, description, price);
}
}
class Sku {
private String code;
private String description;
private BigDecimal price;
Sku(String code, String description, BigDecimal price) {
this.code = code;
this.description = description;
this.price = price;
}
//getters setters methods
}
class Store {
private List<Sku> skus;
Store(SkuFile file) {
skus = file.readAllSku();
}
}
class Test {
public static void main(String[] args) {
Store store = new Store(new SkuFile("products.txt"));
}
}
One way to handle this is by making the parse method return a list of tokenizers(e.g. List tokenizeList) and a second method which takes that list as input and populates the SkuArrayList
Possible implementation of the parser method
public List<String[]> parser() {
List<String[]> tokenizeList = new ArrayList<>();
try {
... /*file opening logic*/
while (fileRead != null)
{
.../*line counting logic*/
String[] tokenize = fileRead.split("\t");
tokenizeList.add(tokenize);
fileRead = br.readLine();
}
// close file stream
br.close();
}// handle exceptions
catch (FileNotFoundException fnfe)
{
System.out.println("file not found");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return tokenizeList;
}
Possible implementation of the populate store method
public void populateStore(List<String[]> tokenizeList) {
for(String[] tokenize: tokenizeList) {
String tempProductCode = tokenize[0];
String tempDescription = tokenize[1];
BigDecimal tempPrice = new BigDecimal(tokenize[2]);
SKU tempObj = new SKU();
tempObj.setProductCode(tempProductCode);
tempObj.setDescription(tempDescription);
tempObj.setPrice(tempPrice);
// add to array list
Store.mySkuArrayList.add(tempObj);
}
}
And the main method from where you call these two methods
public void foo() {
populateStore(parser());
}

Java writer only writing last element of arraylist [duplicate]

This question already has answers here:
Why does the last object get copied multiple times in an ArrayList?
(2 answers)
Closed 7 years ago.
Here is my problem, I have an arraylist of objects which I wish to write to a a text file. For the most part this works but rather annoyingly it only writes the last element of the arraylist. My code is as follows:
public void write() throws IOException {
try {
File file = new File("C:\\contacts.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for(contacts contact:contactList) {
StringBuffer contactrec=new StringBuffer();
contactrec.append(contacts.getID());
contactrec.append(",");
contactrec.append(contacts.getName());
contactrec.append(",");
contactrec.append(contacts.getNotes());
bw.write(contactrec.toString());
bw.newLine();
System.out.println("Contacts have been updated");
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If the arraylist was say the size of 3 the writer would write the last element of the arraylist 3 times to the file. So if the last element was :
"12,John Doe,fish" the text file would have:
12,John Doe,fish
12,John Doe,fish
12,John Doe,fish
written in it. I want to know how to fix and why it happens, any help is appreciated thanks in advance.
My contacts class is this and is populated with objects read from a csv file:
public class contacts {
private static String ID;
private static String Name;
private static String Notes;
public contacts(String ID, String Name, String Notes){
this.ID = ID;
this.Name = Name;
this.Notes = Notes;
}
public static String getID(){
return ID;
}
public static String getName(){
return Name;
}
public static String getNotes(){
return Notes;
}
#Override
public String toString(){
return("ID = " + this.getID() + " " + "Name = " + this.getName()+ " " + "Notes = " + this.getNotes());
}
}
You are using static methods , so everything is related to the contacts class and not the object contact.
So change the data accessor methods to non static. Populate the objects correctly and then in the for loop instead of using contacts use contact.

writeFile() method not working

I am trying to write to a text file. I am able to write to the console however, i am not able to write to my text file. One thing i have noticed is that String data doesn't contain any data if i were to just print to the console which is probably why nothing appears in my textfile. Does anyone know why that is though and how i can come about it?
writeFile() method code:
public static void writeFile(String filename, String content) throws IOException
{
try
{
Files.write(Paths.get(filename), content.getBytes()); // write file
}
catch (IOException e)
{
System.out.println("Error writing file: " + e);
}
}
Test code:
public class QuickTest {
public static void main(String... p) throws IOException {
List<SensorInfo> readings = new ArrayList<>();
SensorInfo info = null;
String data = createStringFromInfo(readings);
writeFile("datastore.txt", data);
String filedata = readFile("client-temp.txt");
List<SensorInfo> temps = createInfoFromData(filedata);
System.out.println(header());
for (SensorInfo reading : temps) {
System.out.print(reading.display());
}
}
}
CreateFromInfo Method:
public static String createStringFromInfo(List<SensorInfo> infoList)
{
String data = "";
for (SensorInfo info : infoList)
{
data += info.asData();
}
return data;
}
createInfoFromData
public static List<SensorInfo> createInfoFromData(String data)
{
List<SensorInfo> infoList = new ArrayList<>();
String[] lines = data.split("\n");
for (String line : lines)
{
SensorInfo info = new SensorInfo(line);
infoList.add(info);
}
return infoList;
}
That implementation of createStringFromInfo() confirms my guess: it will return an empty string when its argument is an empty list, as is the case in your program. I agree with you that that is why you get an empty file.
You fix it by filling the readings list with SensorInfo objects describing the information you want written to the file (before you invoke createStringFromInfo()). If the data for those SensorInfo objects should come from reading file "client-temp.txt" then you should read it in first, then pass that List to createStringFromInfo() to get the data to write.

Categories