Method that Writes an array as text to file read by humans - java

I have a practice question that asks me to write a method that receives an array of employees and a file name. It writes the individual employee (salesman or technician) info as text to a file which can be read by humans. This is the code i have so far
public static void writeAsText (employees[], String fileName)throws IOException
{
// Write the text to the file
File myFile = new File("text.dat");
FileWriter myWriter = new FileWriter(myFile);
BufferedWriter myBufferOut = new BufferedWriter(myWriter);
//Loops through array
for (int i = 0; i < employees.length; i++)
{
myBufferOut.write(employees[i]+"");
}
myBufferOut.close();
}
Pls i just need your opinion to know if i have answered the question right. Thank you for your help in advance.

Related

Loading a file to a Queue structure

i am trying to load a text file that is holding names of students on a waitlist so that i can add them to the queue. when i try to do it this way i am getting errors. does anyone know how i can keep my waitList saved even when i close my program and reopen it?
public void loadWaitList() throws FileNotFoundException {
File wait = new File("waitList.txt");
Scanner waiting = new Scanner(wait);
String first,last,id;
saveClose();
for(int i =0; i < waiting.nextLine().length(); i++) {
first = waiting.next();
last = waiting.next();
id = waiting.next();
Student add =new Student(first,last,id);
waitList.add(add);
}
System.out.println(waiting.nextLine());
waiting.close();
}

Reading file containing random numbers, sorting it and than writing to other file

In an interview I was asked the following question,
There is a file named sourceFile.txt containing random numbers aligned one below other like below,
608492
213420
23305
255572
64167
144737
81122
374768
535077
866831
496153
497059
931322
same number can occur more than once. The size of sourceFile.txt is around 65GB.
I need to read that file and write the numbers into new file lets say destinationFile.txt in sorted order.
I wrote the following code for this,
/*
Copy the numbers present in the file, store in
list, sort it and than write into another file.
*/
public static void readFileThanWrite(String sourceFileName,String destinationFileName) throws Exception{
String line = null;
BufferedReader reader = new BufferedReader(new FileReader(sourceFileName));
List<Integer> list = new ArrayList<Integer>();
do{
if(line != null){
list.add(Integer.parseInt(line));
}
line = reader.readLine();
}while(line != null);
Collections.sort(list);
File file = new File(destinationFileName);
FileWriter fileWriter = new FileWriter(file,true); // 'True' means write content to end of file
BufferedWriter buff = new BufferedWriter(fileWriter);
PrintWriter out = new PrintWriter(buff);
for(Iterator<Integer> itr = list.iterator();itr.hasNext();){
out.println(itr.next());
}
out.close();
buff.close();
fileWriter.close();
}
But the interviewer said the above program will fail to load and sort numbers as the file is large.
What should be the better solution ?
If you know that all the numbers are relatively small, keeping an array of occurences would do just fine.
If you don't have any information about the input, you're looking for external sorting. Here's a Java project that could help you, and here is the corresponding class.

Java: Need Help Reading a large file into an array list by paragraph

OK here is my question, I am in an introductory course in Java so I cannot use any advanced code. I am needing to read in a large text file and store each paragraph as an address in an array list. So I am needing to read in the file and split on the carriage return. What I have so far is posted below. Thanks in advance.
public static void fileReader(String x)throws FileNotFoundException{
String fileName = (x + ".txt");
File input= new File(fileName);
Scanner in =new Scanner(input);
ArrayList<String> linesInFile = new ArrayList<>();
while (in.hasNextLine()){
if ( != '/n'){ //this is where i'm losing it
String line = in.nextLine();
linesInFile.add(line);
}
}
in.close();
If the text file contains paragraphs (doesn't contain any line-breaks within the paragraph), then you don't have to check "/n".
while (in.hasNextLine()){
String line = in.nextLine();
linesInFile.add(line);
}
This would suffice

updating specific cell csv file using java

Hi i have a small problem and think i'm just not getting the correct syntax on one line of code. basically, i can write into my csv file and find a specific record using string tokenizer but it is not updating/editing the specified cells of that record. the record remains the same. please help....
I have used http://opencsv.sourceforge.net in java
Hi,
This is the code to update CSV by specifying row and column
/**
* Update CSV by row and column
*
* #param fileToUpdate CSV file path to update e.g. D:\\chetan\\test.csv
* #param replace Replacement for your cell value
* #param row Row for which need to update
* #param col Column for which you need to update
* #throws IOException
*/
public static void updateCSV(String fileToUpdate, String replace,
int row, int col) throws IOException {
File inputFile = new File(fileToUpdate);
// Read existing file
CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
List<String[]> csvBody = reader.readAll();
// get CSV row column and replace with by using row and column
csvBody.get(row)[col] = replace;
reader.close();
// Write to CSV file which is open
CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
writer.writeAll(csvBody);
writer.flush();
writer.close();
}
This solution worked for me,
Cheers!
I used the below code where I will replace a string with another and it worked exactly the way I needed:
public static void updateCSV(String fileToUpdate) throws IOException {
File inputFile = new File(fileToUpdate);
// Read existing file
CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
List<String[]> csvBody = reader.readAll();
// get CSV row column and replace with by using row and column
for(int i=0; i<csvBody.size(); i++){
String[] strArray = csvBody.get(i);
for(int j=0; j<strArray.length; j++){
if(strArray[j].equalsIgnoreCase("Update_date")){ //String to be replaced
csvBody.get(i)[j] = "Updated_date"; //Target replacement
}
}
}
reader.close();
// Write to CSV file which is open
CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
writer.writeAll(csvBody);
writer.flush();
writer.close();
}
You're doing something like this:
String line = readLineFromFile();
line.replace(...);
This is not editing the file, it's creating a new string from a line in the file.
String instances are immutable, so the replace call you're making returns a new string it does not modify the original string.
Either use a file stream that allows you to both read and write to the file - i.e. RandomAccessFile or (more simply) write to a new file then replace the old file with the new one
In psuedo code:
for (String line : inputFile) {
String [] processedLine = processLine(line);
outputFile.writeLine(join(processedLine, ","));
}
private String[] processLine(String line) {
String [] cells = line.split(","); // note this is not sufficient for correct csv parsing.
for (int i = 0; i < cells.length; i++) {
if (wantToEditCell(cells[i])) {
cells[i] = "new cell value";
}
}
return cells;
}
Also, please take a look at this question. There are libraries to help you deal with csv.
CSV file is just a file. It is not being changed if you are reading it.
So, write your changes!
You have 3 ways.
1
read line by line finding the cell you want to change.
change the cell if needed and composite new version of current line.
write the line into second file.
when you finished you have the source file and the result file. Now if you want you can remove the source file and rename the result file to source.
2
Use RandomAccess file to write into specific place of the file.
3
Use one of available implementations of CSV parser (e.g. http://commons.apache.org/sandbox/csv/)
It already supports what you need and exposes high level API.

Output/Input of Java Files via GUI

I have three classes libraryDB, libraryItems and libraryGUI. libraryDB() is essentially a hash map with the keys as book barcodes/ISBN's and the values are libraryItems, which consist of and therefore take two String parameters: Title and Author.
I have a JFileChooser all set up in the GUI to save, but my save() and open() methods are giving problems. I want it set up so that when it is saved each libraryDB object has its own 3 lines (one each for Barcode, Title, Author, respectively). I tried loading them back in by reading each individual line in, here is the code I wrote for that:
//Suppose to construct a LibraryDB by reading one from a previously-saved file.
public LibraryDB (File file) throws IOException {
Scanner readFile = new Scanner(file);
int barcode;
String title;
String author;
while (readFile.hasNext()){
barcode = Integer.parseInt(readFile.nextLine());
title = readFile.nextLine();
author = readFile.nextLine();
LibraryItem authorTitleValues = new LibraryItem(title,author);
this.libraryItems.put(barcode, authorTitleValues);
}
}
//Trying to save to text file, where for each object n there are 3n lines.
public void save(File file) throws IOException {
PrintStream writer = new PrintStream(file);
for (Iterator<Integer> localIterator = libraryItems.keySet().iterator();
localIterator.hasNext();){
int barcode = ((Integer)localIterator.next()).intValue();
writer.println(barcode);
writer.println((libraryItems.get(Integer.valueOf(barcode))).getTitle());
writer.println((libraryItems.get(Integer.valueOf(barcode))).getAuthor());
}
}
Any help or insight that you can provide that will aid me in successfully being able to save/open would be much appreciated! Thanks!
More explicity, whenever I save a libraryDB to a file I am unable to go back later and open up the file?
You should flush() and close() your PrintStream before ending the save function. I'm not sure that is the problem, since your description is not too accurate, but do it anyway.
File streams and writer have to be explicitly closed at the end of writing to them - otherwise they will lock the file.
public void save(File file) throws IOException {
PrintStream writer = new PrintStream(file);
try {
for (Iterator<Integer> localIterator = libraryItems.keySet().iterator(); localIterator.hasNext();) {
int barcode = ((Integer) localIterator.next()).intValue();
writer.println(barcode);
writer.println((libraryItems.get(Integer.valueOf(barcode))).getTitle());
writer.println((libraryItems.get(Integer.valueOf(barcode))).getAuthor());
}
writer.flush();
} finally {
writer.close();
}
}
So, I just forgot to redeclare libraryDB!? Grrr...lol I don't think the compiler will complain because it has already been declared. However, the information being read from the file was just going into oblivion or something because there was no object for it to be put into. At least, that is what I think was happening. Thanks for your help. Here is my solution:
public LibraryDB (File file) throws IOException {
//this next line was what I was missing...sigh.
this.libraryItems = new HashMap<Integer, LibraryItem>();
Scanner readFile = new Scanner(file);
int barcode;
String title;
String author;
while (readFile.hasNext()){
barcode = Integer.parseInt(readFile.nextLine());
title = readFile.nextLine();
author = readFile.nextLine();
LibraryItem authorTitleValues = new LibraryItem(title, author);
libraryItems.put(Integer.valueOf(barcode), authorTitleValues);
}
readFile.close();
}

Categories