VIP group of companies introduce a new shopping mall “Le Le” . To promote the mall they had approached “6th Event” a famous commercial event organizer to organize an event of lucky draw. The organizer has to collect name, phone and email id of all the visitors during promotion time and give it to the company.
The organizer needs an automated application and wants to store records in a text file called “visitors.txt”.
Records should to be stored in the following structure
Name1,phonenumber1,emailId1;Name2,phonenumber2,emailId2;
In a record, each attributes should be separated using comma (,) and records should be separated using semi colon (;).
Create a Java Application which has two classes called Main.java and FileManager.java
In FileManager class implement the following methods [method skeletons are given]
static public File createFile() – This method should create the file and return it.
static public void writeFile(File f, String record) – In the method, first parameter is the file reference in which records to be added and second parameter is a record, This record should append in the file. [Record should be as per the given format]
static public String[] readFile(File f) – This method accept file to be read, returns all records in the file.
[Note : Don’t modify the signature of the given methods]
In Main class use the following Input and Output statements and call the needed methods from FileManager class to manipulate files.
Enter Name
John
Enter Phone Number
1234567
Enter Email
johnpeter#abc.com
Do you want to enter another record(yes/no)
yes
Enter Name
Grace
Enter Phone Number
98765412
Enter Email
gracepaul#xyz.com
Do you want to enter another record(yes/no)
no
Do you want to display all records(yes/no)
yes
John,1234567,johnpeter#abc.com
Grace,98765412,gracepaul#xyz.com
FileManager class
//import necessary packages
import java.io.*;
import java.util.*;
#SuppressWarnings("unchecked")//Do not delete this line
public class FileManager
{
static public File createFile()
{
File file =new File("visitors.txt");
try{ file.createNewFile();}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
return file;
}
//change the return type as per the requirement
static public void writeFile(File f, String record)
{ try {
BufferedWriter out = new BufferedWriter(
new FileWriter(f.getName(), true));
out.write(record+";");
out.close();
}
catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
static public String[] readFile(File f)
{
List<String> tokens = new ArrayList<String>();
try{
File myObj = new File(f.getName());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
// String [] arr= myReader.nextLine().split(";");
// tokens = Arrays.asList(arr);
tokens.add(myReader.nextLine());
}
myReader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
String[] tokenArray = tokens.toArray(new String[0]);
//=tokenArray.split(";");
return tokenArray;
}
}
Main class
import java.util.*;
import java.io.FileNotFoundException;
//import necessary packages
import java.io.File;
#SuppressWarnings("unchecked")//Do not delete this line
public class Main
{
public void abcd(){
Scanner in = new Scanner(System.in);
System.out.println("Enter Name");
String name=in.next();
System.out.println("Enter Phone Number");
long phone=in.nextLong();
System.out.println("Enter Email");
String id= in.next();
FileManager f= new FileManager();
File x =f.createFile();
f.writeFile(x,name+","+phone+","+id);
System.out.println("Do you want to enter another record(yes/no)");
String choice=in.next();
if(choice.equals("yes")){
abcd();
}
if(choice.equals("no"))
{String []q=f.readFile(x);
String pl[]=q[0].split(";");
for(int i=0;i<pl.length;i++)
{
System.out.println(pl[i]);
}
System.exit(0);
}
}
public static void main(String[] args)
{
Main asd=new Main();
asd.abcd();
}
}
This program gives me desired output but not able to run all test cases.
Getting error could not append multiple files. Dont know is this.But it works perfectly on compiler. And you should at least try to code rather then simply asking someone to code.
//all test case passed
import java.io.*;
import java.util.*;
#SuppressWarnings("unchecked")//Do not delete this line
public class FileManager
{
static public File createFile()
{
File myObj = new File("visitors.txt");
try{
if(new File("visitors.txt").isFile()==false)
myObj.createNewFile();
}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
return myObj;//change the return type as per the requirement
}
static public void writeFile (File f, String record)
{
try
{
FileWriter fw = new FileWriter(f.getName(),true); //the true will append the new data
fw.write(record+"\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
static public String[] readFile(File f)
{
List<String> list=new ArrayList<String>();
try{
File myObj = new File(f.getName());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String str=myReader.nextLine();
String[] parts = str.split(";");
for (String part : parts) {
list.add(part);
}
}
myReader.close();
}
catch(FileNotFoundException ex){}
String[] strings = list.stream().toArray(String[]::new);
return strings;
//change the return type as per the requirement
}
}
Related
I have a record in a CSV file and i am trying to add some extra info (a name) to the same specific record with the following code but it does not work. There is no error shown but the info i am trying to add just does not appear. What am i missing ?
public class AddName {
public static void main(String[] args) {
String filepath="Zoo.csv";
String editTerm="Fish";
String addedName="Ron";
addToRecord(filepath,editTerm,addedName);
}
public static void addToRecord(String filepath,String editTerm,String addedName){
String animal= "";
try{
FileWriter fw=new FileWriter(filepath,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
if (animal.equals(editTerm)){
pw.println(editTerm+","+addedName);
pw.flush();
pw.close();
}
System.out.println("Your Record was saved");
}
catch(Exception e){
System.out.println("Your Record was not saved");
e.printStackTrace();
}
}
You could consider using a CSV library to help you out with parsing CSVs because it is more complicated than it looks, especially when it comes down to quoting.
Here's a quick example using OpenCSV that clones the original CSV file and adds "Ron" as necessary:
public class Csv1 {
public static void main(String[] args) throws IOException, CsvValidationException {
addToRecord("animal.csv", "animal-new.csv", "fish", "Ron");
}
public static void addToRecord(String filepathIn, String filepathOut, String editTerm, String addedName)
throws IOException, CsvValidationException {
try (CSVReader reader = new CSVReader(new FileReader(filepathIn))) {
try (CSVWriter writer = new CSVWriter(new FileWriter(filepathOut))) {
String[] values;
while ((values = reader.readNext()) != null) {
if (values.length > 2 && values[0].equals(editTerm)) {
values[1] = addedName;
}
writer.writeNext(values);
}
}
}
}
}
Given the file:
type,name,age
fish,,10
cat,,12
lion,tony,10
will produce:
"type","name","age"
"fish","Ron","10"
"cat","","12"
"lion","tony","10"
(You can look for answers about outputting quotes in the resulting CSV)
Here the requirement is to add an extra column if the animal name matches. It's equivalent to changing a particular line in a file. Here's a simple approach to achieve the same, (Without using any extra libraries),
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class EditLineInFile {
public static void main(String[] args) {
String animal = "Fish";
Path path = Paths.get("C:\\Zoo.csv");
try {
List<String> allLines = Files.readAllLines(path);
int counter = 0;
for (String line : allLines) {
if (line.equals(animal)) {
line += ",Ron";
allLines.set(counter, line);
}
counter++;
}
Files.write(path, allLines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You may use this code to replace the file content "Fish" to "Fish, Ron"
public static void addToRecord(String filepath, String editTerm, String addedName) {
try (Stream<String> input = Files.lines(Paths.get(filepath));
PrintWriter output = new PrintWriter("Output.csv", "UTF-8"))
{
input.map(s -> s.replaceAll(editTerm, editTerm + "," + addedName))
.forEachOrdered(output::println);
} catch (IOException e) {
e.printStackTrace();
}
}
I'm attempting collect all the methods in a Java file using the Eclipse AST package. I believe that I have the CompilationUnit created successfully. However when I attempt to use a visitor to collect the information it doesn't go past the main() method of the file I'm testing.
public void parseCode(String fileName) {
String strSource = "";
try {
strSource = codeToString(fileName);
} catch (Exception e) {
e.printStackTrace();
}
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setSource(strSource.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(new NullProgressMonitor());
SCTVisitor v = new SCTVisitor();
cu.accept(v);
System.out.println(v.m);
}
public class SCTVisitor extends ASTVisitor{
List<SimpleName> m = new ArrayList<SimpleName>();
SCTVisitor(){
System.out.println("What is love");
}
#Override public boolean visit(MethodInvocation node) {
this.m.add(node.getName());
return true;
}
}
This is part of the file I'm using to test:
import java.util.Map;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
public class WordCount {
public static void main(String[] args) {
System.out.println("Cheese");
countWordsViaGUI();
}
// allow user to pick file to exam via GUI.
// allow multiple picks
public static void countWordsViaGUI() {
setLookAndFeel();
try {
Scanner key = new Scanner(System.in);
do {
System.out.println("Opening GUI to choose file.");
Scanner fileScanner = new Scanner(getFile());
Stopwatch st = new Stopwatch();
st.start();
ArrayList<String> words = countWordsWithArrayList(fileScanner);
st.stop();
System.out.println("time to count: " + st);
System.out.print("Enter number of words to display: ");
int numWordsToShow = Integer.parseInt(key.nextLine());
showWords(words, numWordsToShow);
fileScanner.close();
System.out.print("Perform another count? ");
} while(key.nextLine().toLowerCase().charAt(0) == 'y');
key.close();
}
catch(FileNotFoundException e) {
System.out.println("Problem reading the data file. Exiting the program." + e);
}
}
My results are:
[println, countWordsViaGUI]
My expected results are:
[println, countWordsViaGUI, setLookAndFeel, scanner, println, getFile, Scanner, ...]
Please let me know if you have any insight into this problem.
So in my main class called testPara, whenever I want to execute the methods in my class paragraph, I always have to write the file name inside the parameter of my methods. For example: g.readFile(file), g.countSentence(file). What would I have to do so methods won't require and I could execute just by g.count(). Maybe a global variable? This my paragraph class:
import java.util.*;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class paragraph {
public void readFile(File filename) {
try {
Scanner scanner = new Scanner(filename);
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
}
public void countSentences(File filename) {
int sentanceCount = 0;
String line;
String delimiters = "?!.";
try {
Scanner scanner = new Scanner(filename);
while(scanner.hasNextLine()) {
line = scanner.nextLine();
for(int i = 0; i < line.length(); i++) {
if (delimiters.indexOf(line.charAt(i)) != -1) {
sentanceCount++;
}
}
}
System.out.println("# of sentances: " + sentanceCount);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
}
This is how I'm testing my methods
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class testPara {
public static void main(String args[]) {
paragraph g = new paragraph();
File file = new File("story.txt");
g.readFile(file);
System.out.println("\n");
g.countSentences(file);
}
}
This makes only sense if your Paragraph class works with the same file the whole time. Then you could just add a field private File file; or something to the Paragraph class and use a setter to set the File object once. Like so:
public class Paragraph {
private File file;
public void setFile(File file){
this.file = file;
}
....
...and in the main method:
Paragraph p = new Paragraph();
p.setFile(new File("whatever.txt"));
p.readFile();
p.countSentences();
....
Of course you'll have to modify your readFile() method (etc) so they use the new "file" class variable.
EDIT: Or, as #4castle suggested, you could use a constructor to hand over the File instance (if your class needs this instance to work properly, this would be the right approach).
Make filename an instance variable of your class Paragraph
class Paragraph {
private String filename;
. . .
// constructor taking the argument for filename
public Paragraph(String filename) {
this.filename = filename;
. . .
and have the caller pass the value in when constructing an object from that class
Paragraph g = new Paragraph("story.txt");
After that, your methods do not need the argument anymore, they
can just take the value from the instance variable. For example
public void countSentences() {
Scanner scanner = new Scanner(this.filename);
I am relatively new to Java programming. Recently I decided to create a random system that stores, writes, and reads information on request. When reading a file I have already written with the program, I get the following errors:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at ReadFile.readFile(ReadFile.java:24)
at User.main(User.java:35)
I'm assuming this errors are a result of the User class calling on the ReadFile class, because the rest of the program works fine so far.
The User class that pertains:
import java.io.*;
import java.util.*;
public class User
{
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
Scanner user_input = new Scanner(System.in);
String input;
System.out.println("User Information System:");
System.out.println("Please type the full name of the person you wish to lookup.");
input = user_input.nextLine();
System.out.println("UIS currently has the following data on " + input + ":");
if(input.equals("First Last"))
{
System.out.println("Opening Data on " + input + "...");
}
else
{
System.out.println("No Data found.");
}
if(input.equals("/create"))
{
CreateFile create = new CreateFile();
create.openFile();
create.addRecords();
create.closeFile();
}
if(input.equals("/read"))
{
ReadFile read = new ReadFile();
read.openFile();
read.readFile();
read.closeFile();
}
}
}
As well as the ReadFile class:
import java.io.*;
import java.util.*;
public class ReadFile
{
static Scanner scanner;
public void openFile()
{
try
{
scanner = new Scanner(new File("TestFile.txt"));
}
catch(Exception e)
{
System.out.println("Error reading file.");
}
}
public void readFile()
{
while(scanner.hasNext()) //Find a way to shorten this to a loop of printing whatever is in the file.
{
String a = scanner.nextLine();
String b = scanner.next();
String c = scanner.next();
System.out.printf("%s %s %s\n", a,b,c);
}
}
public void closeFile()
{
scanner.close();
}
}
Ok, I'm really confused by some code I wrote. It's a DataSetter (didn't know a better name for it...), and has methods to change the data in my data file (data.txt). This data has the following format: #key=value (eg. #version=1.0). Now, I tried to run this line of code:
new DataSetter().setValue("version", "1.1");
It just clears the file. That's pretty much all it does. Now, I think it clears the file because it makes a new File, which is completely empty but has the same name. Here's my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/**
* This class contains methods to set specific data in the data.txt file. <br>
* The data is rewritten every time a new value is set.
*
* #author Casper van Battum
*
*/
public class DataSetter {
private static final File DATA_FILE = new File("resources/data.txt");
private static final String lineFormat = "#%s=%s";
private FileOutputStream out;
private DataReader reader = new DataReader();
private HashMap<String, String> dataMap = reader.getDataMap();
private Scanner scanner;
public DataSetter() {
try {
out = new FileOutputStream(DATA_FILE, false);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void setValue(String key, String newValue) {
openDataFile();
String oldLine = String.format(lineFormat, key, dataMap.get(key));
dataMap.put(key, newValue);
String newLine = String.format(lineFormat, key, newValue);
try {
replace(oldLine, newLine);
} catch (IOException e) {
e.printStackTrace();
}
closeDataFile();
}
private void replace(String oldLine, String newLine) throws IOException {
ArrayList<String> tmpData = new ArrayList<String>();
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
tmpData.add((currentLine == oldLine) ? newLine : currentLine);
}
out.write(new String().getBytes());
String sep = System.getProperty("line.separator");
StringBuffer sb = new StringBuffer();
for (String string : tmpData) {
sb.append(string + sep);
}
FileWriter writer = new FileWriter(DATA_FILE);
String outString = sb.toString();
writer.write(outString);
writer.close();
}
private void openDataFile() {
try {
scanner = new Scanner(DATA_FILE);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
private void closeDataFile() {
scanner.close();
}
}
So after running the setValue() method, I just have an empty file...
Im really out of idea's on how to solve this...
You are truncating your data file with the
new FileOutputStream(DATA_FILE, false)
so no nothing is written when you go to output your the elements in the tmpData ArrayList read from Scanner.
ArrayList<String> tmpData = new ArrayList<String>();
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine(); // never gets called
...
}
The typical strategy for updating a text file is to create a temporary file with old file's contents (File#renameTo), write the data to file, then delete the temporary file after closing any open streams to the file being read.