How to create fixed format file using FixedFormat4j Java Library? - java

I am able to load files in Fixed Format but unable to write a fixed format file using FixedFormat4j.
Any idea how to do that?
public class MainFormat {
public static void main(String[] args) {
new MainFormat().start();
}
private FixedFormatManager manager;
public void start(){
System.out.println("here");
manager = new FixedFormatManagerImpl();
try {
BufferedReader br = new BufferedReader(new FileReader("d:/myrecords.txt"));
System.out.println("here1");
String text;
MyRecord mr = null;
while ((text = br.readLine()) != null) {
mr = manager.load(MyRecord.class, text);
System.out.println(""+mr.getAddress() + " - "+mr.getName());
}
mr.setName("Rora");
manager.export(mr);
} catch (IOException | FixedFormatException ex) {
System.out.println(""+ex);
}
}
}
I have seen export method but don't understand how to use it? Nothing happens in above code

The export method returns a string representing the marshalled record.
In your code you would need to write out the result of the export command to a FileWriter. So:
before the while loop:
FileWriter fw = new FileWriter("d:/myrecords_modified.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
after the while loop:
mr.setName("Rora");
String modifiedRecord = manager.export(mr);
bw.write(modifiedRecord);

Related

Add Fileinput to Treemap

I can't add the file input to my map. It says I am missing something and that the Items []is not instantiated. I can't seem to figure it out
public class BigCities {
private Map<String, Set<CityItem>> countryMap;
private File file;
public BigCities(String fileName) {
countryMap = new TreeMap<>();
file = new File(fileName);
readFile(fileName);
}
private void readFile(String fileName) {
// Opg 3c implementeres her.
CityItem cityItem;
try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
String[] items;
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line.split(";");
line = br.readLine();
cityItem = new CityItem(items[1], items[2], items[3]);
}
String everything = sb.toString();
System.out.println(everything);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String toString() {
return countryMap.toString();
}
/**
* #param args
*/
public static void main(String[] args) {
//Vaelg ANSI eller UTF8 afhaengig af hvad der virker bedst paa din computer:
BigCities bc = new BigCities("EuroCities ANSI.txt");
//BigCities bc = new BigCities("EuroCities UTF8.txt");
System.out.println(bc);
}
}
I Don't know what I am missing to add the input, but hopefully someone has some input.
I Am new to programming and therefore I find it confusing, since I feel like I am following all the right methods.
You never initialize the items array, so when trying to access it, you're getting null, or it may just be caught by the compiler and will give you an error there.
I suspect that you mean to assign the split to items, so change the line
line.split(";");
to
items = line.split(";");

Buffered Writer not writing to txt file from ArrayList

I am having a spot of bother getting BufferedWriter to write output to a txt file I have.
When I compile the program, I do not get any errors but the txt file arrives in my project blank.
I have looked on here at similar questions and tried a few of the proposed solutions to resolve it without success, like closing the stream etc
public void storeToDoItemsOntoTxtFile () throws IOException {
Path path = Paths.get(fileName);
BufferedWriter buffyWriter = Files.newBufferedWriter(path);
try {
Iterator<ToDoItem> bigIterator = toDoItems.iterator();
while (bigIterator.hasNext()) {
ToDoItem item = bigIterator.next();
buffyWriter.write(String.format("%s\t%S\t%s", item.getShortDescription(), item.getDetails(), item.getDeadline().format(formatter)));
buffyWriter.newLine();
}
} finally {
if (buffyWriter !=null) {
buffyWriter.close();// when we are done working with the writer
}
}
}
BufferedReader
public void loadToDoItemsFromTxtFile() throws IOException {
toDoItems = FXCollections.observableArrayList();
Path path = Paths.get(fileName);
BufferedReader buffyReader = Files.newBufferedReader(path);
String buffyInput;
try {
while ((buffyInput = buffyReader.readLine()) !=null) {
String [] itemPieces = buffyInput.split("\t");
String shortDescription = itemPieces[0];
String details = itemPieces[1]; //
String dateString = itemPieces [2];
LocalDate date = LocalDate.parse(dateString, formatter);
ToDoItem toDoItem = new ToDoItem(shortDescription,details,date);
toDoItems.add(toDoItem);
}
} finally {
if (buffyReader != null) {// ie the buffy reader states that there is a toDoItem" in the txt file
buffyReader.close();
}
}
}

Java, passing values between classes

Ok so I'm a noob at Java and this just got me.
I have a button that calls a class in which some background code runs to check if the tape drive is online, offline or busy.
Button Code:
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
btnRunBackup runBackupObject = new btnRunBackup();
runBackupObject.checkStatus();
lblRunBck.setText("Errors go here");
}
Then I have my separate class file btnRunBackup.
public class btnRunBackup{
public void checkStatus(){
/*
Here I simply create a tempfile and run some
linux commands via getRuntime and print the
output to the tempfile
Then I call my second method passing the
absolute file path of the tempfile
*/
this.statusControl(path);
}catch(IOException e){
e.printStackTrace();
public void statusControl(String param) throws FileNotFoundException, IOException{
/*
Here I use BufferedReader to go through the
tempfile and look for as series of 3
different strings.
I use a if else if statement for flow control
depending on what string was found.
string 1 will call a new Jframe
if string 2, 3 or none of them are found the
is where I am stuck at
}
}
I want to return a String value back to btnRunBckActionPerformed().
The reason is lblRunBck will initially show no text at all but for instance the user clicks on the button and the resource happens to be busy then i want to run lblRunBck.setText(param); on lblRunBck while refusing the user permission to continue
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String text;
btnRunBackup runBackupObject = new btnRunBackup();
runBackupObject.checkStatus();
lblRunBck.setText("Errors go here");
}
here is my btnRunBackup class
public class btnRunBackup {
private String s;
public void checkStatus() {
String s, path = null;
Process p;
try{//try1
//create a temp file named tempfilexxx.tmp
File temp = File.createTempFile("tempfile", ".tmp");
//get file path
path = temp.getAbsolutePath();
System.out.println("checkStatus: " + path);
//write to tempfilexxx.tmp
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
try{// try2
//set p = to the content of ls home
p = Runtime.getRuntime().exec("ls /home | grep ariel");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
//write content of p to tempfilexxx.tmp line by line
while ((s = br.readLine()) != null)
bw.write(s + "\n");
//close BufferedReader
br.close();
}catch (Exception e){} //END OF try2
//close BufferedWriter
bw.close();
/*
Now that we ran the 'mt -f /dev/nst0 status command under home we
will filter for one of the following strings
(for testing we will use ls -la /home and filter for ariel)
We will do this by calling the checkStatus method
*/
this.statusControl(path);
}catch(IOException e){
e.printStackTrace();
}// END OF try1
}// END OF listDir
//throws FileNotFoundException for bufferedReader if file not found
public void statusControl(String param) throws FileNotFoundException, IOException{
/*
On production code there will be 4 possible conditions:
1. ONLINE - ready to write (currently we will use ariel)
2. DR_OPEN - no tape available
3. /dev/nst0: Device or resource busy - resource bussy
4. If other than stated above give error 1000
*/
System.out.println("statusControl: " + param);
String ONLINE = "arielvz",
OPEN = "DR_OPEN",
BUSSY = "Device or resource busy",
sCurrentLine;
//Scan file line by line for one of the above options
BufferedReader br = new BufferedReader(new FileReader(param));
while ((sCurrentLine = br.readLine()) != null){
//Tape is online and ready for writing
if (sCurrentLine.contains(ONLINE)){
System.out.println("found ariel");
}
//There is no tape in the tape drive
else if (sCurrentLine.contains(OPEN)){
//lblRunBck should tell the user to put a tape in the drive
System.out.println("No tap in tape drive");
}
else if (sCurrentLine.contains(BUSSY)){
//lblRunBck should notify user that the resource is in use
System.out.println("Device or resource bussy");
}
else{
//Something unexpected happend
System.out.println("Error 1001: Please notify Administrator");
}
}
}//END OF statusControl
public String returnHandler(String param){
return param;
}
}
Maby This will make it more clear
If you want checkStatus to return a status, then do not make it returning nothing (a void function)
public class btnRunBackup {
private String s;
public void checkStatus() {
but make it returning error as a String like:
public class btnRunBackup {
private String s;
public String checkStatus() {
String error = null; // by default no error
... do whatever you need to find out the error
....
error = "error is: xxx ";
return error; // return null (no error ) or what you found
}
change you logic in you calling code to display what error have been returned by checkStatus
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
String error;
btnRunBackup runBackupObject = new btnRunBackup();
error = runBackupObject.checkStatus();
lblRunBck.setText(error == null ? "No error" : error);
}

Error while running customized java class

I have created a sequence file out of directory and then given index according to groups I want so that I can create groups using that index. This groups are then given one by one to my customized java class which gives information based on the file present in the group.
My problem is that some time it runs perfectly but some time gives different errors like null pointer exception, data type of field not found.
The problem is may be due to size of group. Because I am creating folder based group and then do the fetches the information from that folder inside my customized jar.
So how can I resolve this issue?
Below is my java class code:
public class OperateDirectory extends EvalFunc<DataBag>{
public TupleFactory tupleFactory = TupleFactory.getInstance();
public BagFactory bagFactory = BagFactory.getInstance();
public DataBag exec(Tuple input) throws IOException{
ArrayList<String> protoTuple = new ArrayList<>();
DataBag dataBag = bagFactory.newDefaultBag();
/* Create Directory */
if(input == null)
return dataBag;
if(input.size() != 2)
return dataBag;
long id = (long)input.get(0);
DataBag infoBag = (DataBag)input.get(1);
Iterator<Tuple> it = infoBag.iterator();
File dir = new File("/tmp/TestFolder"+id);
if(dir.exists())
{
FileUtils.cleanDirectory(dir);
}
else
{
dir.mkdir();
}
while(it.hasNext())
{
Tuple file_details = (Tuple)it.next();
if(file_details != null && file_details.size()==3)
{
String file_name = (String)file_details.get(1);
BytesWritable file_contents = (BytesWritable)file_details.get(2);
File f = new File(dir.getPath()+"/"+file_name);
f.deleteOnExit();
writeToFile(file_contents, f);
}
}
/* Perform operation here */
File f = new File("output"+id+".log");
ProcessBuilder performProcess1 = new ProcessBuilder("processes/processor", dir.getPath(),f.getPath());
Process process1 = performProcess1.start();
try
{
process1.waitFor();
if(f.exists() && f.length()>0)
{
ProcessBuilder performProcess2 = new ProcessBuilder("perl", "scripts/ParseFile.pl", f.getPath());
Process process2 = performProcess2.start();
InputStream is = process2.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
if(!line.isEmpty())
{
String [] tmpArray = line.split(",");
if(tmpArray.length == 2)
{
protoTuple.clear();
protoTuple.add(tmpArray[0]);
protoTuple.add(tmpArray[1]);
dataBag.add(tupleFactory.newTuple(protoTuple));
}
}
}
}
else
{
protoTuple.clear();
protoTuple.add("Error");
protoTuple.add("File "+f.getPath()+" does not exists ");
dataBag.add(tupleFactory.newTuple(protoTuple));
}
}
catch(Exception e)
{
protoTuple.clear();
protoTuple.add("Error ");
protoTuple.add(e.getMessage());
dataBag.add(tupleFactory.newTuple(protoTuple));
}
try
{
FileUtils.cleanDirectory(dir);
FileUtils.deleteDirectory(dir);
}
catch(Exception e)
{
}
return dataBag;
}
void writeToFile(BytesWritable value, File binaryFile) throws IOException{
FileOutputStream fileOut = new FileOutputStream(binaryFile);
fileOut.write(value.getBytes(), 0, value.getLength());
fileOut.close();
}
}

Avoid repetition when writing strings to text file line by line

I use the following code to write strings to my simple text file:
EDITED:
private String fileLocation="/mnt/sdcard/out.txt";
public void saveHisToFile()
{
if (prefs.getBoolean("saveHis", true) && mWordHis != null && mWordHis.size() >= 1)
{
StringBuilder sbHis = new StringBuilder();
Set<String> wordSet= new HashSet<String>(mWordHis);
for (String item : wordSet)
{
sbHis.append(item);
sbHis.append("\n");
}
String strHis = sbHis.substring(0, sbHis.length()-1);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
fileLocation), true));
bw.write(strHis);
bw.newLine();
bw.close();
} catch (IOException e) {
}
}
}
The strings are successfully written to the text file, but weirdly, some strings are overwritten, such as:
apple
orange
grapes
grapes
grapes
apple
kiwi
My question is:
how can I stop a string being written more than once?
how can I stop writing a string (a line) to the file if it has already existed in the file?
I have consulted this post but failed to apply it to my case. Can you please give a little help? Thanks a lot in advance.
Try this:
public void saveHisToFile(Set<String> existingWords)
{
if (prefs.getBoolean("saveHis", true) && mWordHis != null && mWordHis.size() >= 1)
{
StringBuilder sbHis = new StringBuilder();
for (String item : mWordHis)
{
if (!existingWords.contains(item)) {
sbHis.append(item);
sbHis.append("\n");
}
}
String strHis = sbHis.substring(0, sbHis.length()-1);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
fileLocation), true));
bw.write(strHis);
bw.newLine();
bw.close();
} catch (IOException e) {
}
}
}
I guess mWordHis is a List, which can contain duplicate entries.
You can first convert it to a Set (which doesn't allow duplicates) and print only the words in the Set.
Set<String> wordSet= new HashSet<>(mWordHis);
for (String item : wordSet)
{
sbHis.append(item);
sbHis.append("\n");
}
As #fge commented, LinkedHashSet may also be used if insertion order matters.
If you need to run the same code several times with the same file, you must either save in memory all the records you've already wrote to the file, or read the file and get all data before writing to it.
Edit:
I can only think about trimming the words as some may contain unneeded spaces:
Set<String> wordSet= new HashSet<>();
for (String item : mWordHis){
wordSet.add(item.trim());
}
This is a complete example on how to solve your problem:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
public class HisSaver {
private HashSet<String> uniqueTester = new HashSet<String>();
private String fileLocation="/mnt/sdcard/out.txt";
private static HisSaver instance = null;
private HisSaver() {
readWordsFromFile();
}
public static HisSaver getInstance() {
if(instance == null)
instance = new HisSaver();
return instance;
}
public void saveWord(String word) {
if(!uniqueTester.contains(word)) {
uniqueTester.add(word);
writeWordToFile(word);
}
}
private void writeWordToFile(String word) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
fileLocation), true));
bw.write(word);
bw.newLine();
bw.close();
} catch (IOException e) {
}
}
private void readWordsFromFile() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(
fileLocation)));
String line;
while((line = br.readLine()) != null) {
if(!uniqueTester.contains(line)) {
uniqueTester.add(line);
}
}
} catch (IOException e) {
}
}
}
Now to use this, you simply do the following in your code:
HisSaver hs = HisSaver.getInstance();
hs.saveWord("newWord");
This will insert the "newWord" if and only if it is not already in your file, provided that no other function in your code accesses this file. Please note: this solution is NOT thread safe!!!
Edit: Explanation of what the code does:
We create a class HisSaver which is a singleton. This is realized by making it's constructor private and providing a static method getInstance() which returns an initialized HisSaver. This HisSaver will already contain all preexisting words in your file and thus only append new words to it. Calling the getInstance() method from another class will give you a handle for this singleton and allow you to call saveWord without having to worry whether you have the right object in your hands, since only one instance of it can ever be instantiated.
You could add all the strings into a HashMap and check for each new String if it is are already in there.
Example:
HashMap<String,String> test = new HashMap<String,String>();
if(!test.containsKey(item)) {
test.put(item,"");
// your processing: example
System.out.println(item);
} else {
// Your processing of duplicates, example:
System.out.println("Found duplicate of: " + item);
}
Edit: or use a HashSet as shown by the other solutions ...
HashSet<String> test = new HashSet<String>();
if(!test.contains(item)) {
test.add(item);
// your processing: example
System.out.println(item);
} else {
// Your processing of duplicates, example:
System.out.println("Found duplicate of: " + item);
}
Edit2:
private String fileLocation="/mnt/sdcard/out.txt";
public void saveHisToFile()
{
if (prefs.getBoolean("saveHis", true) && mWordHis != null && mWordHis.size() >= 1)
{
StringBuilder sbHis = new StringBuilder();
HashSet<String> test = new HashSet<String>();
Set<String> wordSet= new HashSet<String>(mWordHis);
for (String item : wordSet)
{
if(!test.contains(item)) {
test.add(item);
// your processing: example
sbHis.append(item+System.lineSeparator());
} else {
// Your processing of duplicates, example:
//System.out.println("Found duplicate of: " + item);
}
}
String strHis = sbHis.toString();
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
fileLocation), true));
bw.write(strHis);
bw.newLine();
bw.close();
} catch (IOException e) {
}
}
}

Categories