I was asked to write an assignment wherein the user would be prompted to input a key and/or a value.
So far, here is my code:
import java.util.Scanner;
import java.io.*;
class bTree
{
//Fields
static Scanner input = new Scanner(System.in);
static boolean done = false;
public static void main(String args[])throws Exception
{
FileWriter fWriter = new FileWriter("data.txt");
do
{
System.out.print("Enter command: ");
String enter[] = input.nextLine().split(" ", 3);
if(enter[0].toLowerCase().equals("insert"))
{
fWriter.write(enter[1] + "\n" + enter[2] + "\n");
fWriter.flush();
}
else if(enter[0].toLowerCase().equals("select"))
{
FileReader fReader = new FileReader("data.txt");
Scanner fileInput = new Scanner(fReader);
while(fileInput.hasNext() && done == false)
{
if(fileInput.nextLine().equals(enter[1]))
{
System.out.println(fileInput.nextLine());
done = true;
}
else
{
fileInput.nextLine();
}
}
done = false;
}
else if(enter[0].toLowerCase().equals("update"))
{
fWriter.write(enter[2]);
fWriter.flush();
}
else if(enter[0].toLowerCase().equals("exit"))
{
System.exit(0);
}
}
while(true);
}
}
Problem: When i open the data.txt, there are no spaces. So if i enter "insert 1001 gen" and "10001 genny", in notepad, it would come out as "1001gen10001genny". Any suggestions?
The problem is that notepad.exe is picky about line endings, and there are many possibilities. When you write "\n" to a FileWriter, it writes a single character, namely '\n'. But notepad expects the sequence "\r\n" instead. It shows a single "\n" as nothing.
Here is your code, slightly modified to work around some pitfalls.
package so7696816;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
public class Excercise {
public static void main(String args[]) throws Exception {
final Scanner input = new Scanner(System.in);
PrintWriter fWriter = new PrintWriter("data.txt");
while (true) {
System.out.print("Enter command: ");
String enter[] = input.nextLine().split(" ", 3);
final String command = enter[0].toLowerCase(Locale.ROOT);
if (command.equals("insert")) {
fWriter.println(enter[1]);
fWriter.println(enter[2]);
fWriter.flush();
} else if (command.equals("select")) {
FileReader fReader = new FileReader("data.txt");
Scanner fileInput = new Scanner(fReader);
while (fileInput.hasNextLine()) {
String key = fileInput.nextLine();
String value = fileInput.nextLine();
if (key.equals(enter[1])) {
System.out.println(value);
break;
}
}
fReader.close(); // don't leave files open
} else if (command.equals("update")) {
fWriter.write(enter[2]);
fWriter.flush();
} else if (command.equals("exit")) {
return;
} else {
System.err.println("Unknown command: " + command);
}
}
}
}
Remarks:
I used a PrintWriter instead of a FileWriter to get the line endings correct.
For the select command I closed the fReader after using it.
I avoided to type enter[0].toLowerCase() multiple times.
I used the proper variant of toLowerCase.
I added error handling for unknown commands.
I rewrote the select command to be a little more concise.
The problem is String enter[] = input.nextLine().split(" ", 3);, it kills the Spaces. So append a space after each array entry or write an additional " " everytime you use fWriter.write.
look here
As already stated the line feed character is incorrect for notepad. Alternatively you could wrap that FileWriter in a BufferedWriter and use the newLine method to always insert the correct line feed.
I think you are running your program in UNIX. In unix system "\r\n" is the line feed.
If you are running your program in Windows, I think the file should contain something like this.
1001
gen
10001
genny
Related
I have a problem and wanted to ask if someone can help me. I have a Java application that processes CSV files. The files have a semi-colon as a "delimiter". Now instead of semicolons I would like to use pipe "|" as the "delimiter". What is the best way to do this?
I have already informed myself in the library or class "org.apache.commons.csv.CSVRecord". Unfortunately couldn't find anything here.
I used for parsing Spring Batch with the class FlatItemReaderBuilder.
You can also use Spring Batch classes in non Spring application.
Here you can find an example:
https://www.petrikainulainen.net/programming/spring-framework/spring-batch-tutorial-reading-information-from-a-file/
you could use Scanner or FileInputStream
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ReadDelimited {
public static void main(String[] args) {
Scanner sc = null;
try {
sc = new Scanner(new File("D:\\acct.csv"));
// Check if there is another line of input
while(sc.hasNextLine()){
String str = sc.nextLine();
// parse each line using delimiter
parseData(str);
}
} catch (IOException exp) {
// TODO Auto-generated catch block
exp.printStackTrace();
}finally{
if(sc != null)
sc.close();
}
}
private static void parseData(String str){
String acctFrom, acctTo, amount;
Scanner lineScanner = new Scanner(str);
lineScanner.useDelimiter("|");
while(lineScanner.hasNext()){
acctFrom = lineScanner.next();
acctTo = lineScanner.next();
amount = lineScanner.next();
System.out.println("Account From- " + acctFrom + " Account To- " + acctTo +
" Amount- " + amount);
}
lineScanner.close();
}
}
reference Code original link
or if File is not too large get the read the File in a string Divide it into a String array by splitting by line break and then future splitting using the delimiter of choice something like the code below.
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream=new FileInputStream("j:\\test.csv");
String s1=new String(fileInputStream.readAllBytes());
String[] lineArray=s1.split("\n");
List<String[]> separatedValues=new ArrayList<>();
for (String line: lineArray) {
separatedValues.add(line.split("\\|"));
}
for (String[] s: separatedValues) {
for (String s2:s ) {
System.out.print(s2+" ");
}
System.out.println("");
}
fileInputStream.close();
}
Code Output Link
Original CSV
I have a program taking user input and setting students in a text file, I want to sort these students in separate text files using the grade average
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
public class NewClass2
{
public static void main(String[] args)
{
String recOut = "";
String delimiter = ",";
Scanner input = new Scanner(System.in);
final int QUIT = 999;
NewClass1 student = new NewClass1();
try
{
System.out.println("Enter Student ID: ");
student.setStudentId(input.nextInt());
while(student.getStudentId() != QUIT)
{
System.out.println("Enter Student Last Name: ");
student.setLastName(input.next());
System.out.println("Enter Student First Name: ");
student.setFirstName(input.next());
System.out.println("Enter Student Grade Point: ");
student.setGradePoint(input.nextDouble());
if(student.getGradePoint()>=3.6)
{
Path fileOut = Paths.get("HonorsStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter + student.getLastName() + delimiter + student.getFirstName() + delimiter + student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
if(student.getGradePoint()<3.6 && student.getGradePoint()>=2.0)
{
Path fileOut = Paths.get("GoodStandingStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter + student.getLastName() + delimiter + student.getFirstName() + delimiter + student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
if(student.getGradePoint()<2.0)
{
Path fileOut = Paths.get("ProbationStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter
+ student.getLastName() + delimiter
+ student.getFirstName() + delimiter
+ student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
System.out.println("Enter Student ID: ");
student.setStudentId(input.nextInt());
}
}
catch(Exception e)
{
System.out.println("<<Something bad happened!>>");
System.out.println(e.getMessage());
}
}
}
I've been experimenting with if statements but that's not working because I can't close the writer correctly causing it to only take in one line then stopping.
How do I do this correctly?
The problem is not with how you're closing the file but with how your opening the file. Every time you're opening the file you are creating a new file and writing one line, then closing it, which is overwriting the old file that existed before. What you want to do is create the file if it does not exist, but if it does exist append one line.
Simply change
Files.newOutputStream(fileOut, CREATE)
to
Files.newOutputStream(fileOut, CREATE, APPEND)
Alternatively, you could open/close the files outside the loop or use “try with resources” too.
Since these are only three files, it is probably the easiest to open all three writers at once at the start and keep them open until the end.
If you don't want to close the writers manually (ans at least java 7 or 8 i think), you can use a try-with-resources statement.
Btw you probably don't need to wrap the OutputStream in a BufferedOutputStream, since you already use a buffered writer.
Instead of writing each time in file why don't you try to make three lists(one for every grade range you need) and when you have no more students then write them to separate files.
Something like this:
List<Student> honorsStudent = new ArrayList<Student>();
List<Student> goodStandingStudent = new ArrayList<Student>();
List<Student> probationStudent = new ArrayList<Student>();
// ....
if (student.getGrade() >= 3.6) {
honorsStudent.add(student);
} else if (student.getGrade() >= 2) {
goodStandingStudent.add(student);
}
else {
probationStudent.add(student);
}
//while loop end
//write your files
So I'm trying to create a program that takes input in the form of a First and Last Name and then printing it to a Output.txt file.
I'm sort of new to programming, and I think I'm derping on this.
I just keep getting an error on the last part of my program.
PrintInitials.java:21: error: <identifier> expected
} output.close();
^
1 error
Here's my Code
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.*;
public class PrintInitials
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String first; // first name
String last; // last name
System.out.print("Enter your first and last name separated by a space: ");
first = stdIn.next();
last = stdIn.next();
File file = new File("Output.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
} output.close();
}
do it like this:
Scanner stdIn = new Scanner(System.in);
System.out.print("Enter your first and last name separated by a space: ");
String first = stdIn.next(); // first name
String last = stdIn.next(); // last name
stdIn.close();
try (FileWriter writer = new FileWriter(new File("Output.txt"), true); // autocloseable
PrintWriter output = new PrintWriter(writer)) { // autocloseable
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
} catch (IOException e) {
e.printStackTrace();
}
The Writers will be closed automatically.
The problem is that before closing the stream, you are closing the method body. so the 'output.close();' is outside the method and into the class body.
Your new code should look like this:
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.*;
public class PrintInitials{
public static void main(String[] args){
try{
Scanner stdIn = new Scanner(System.in);
String first; // first name
String last; // last name
System.out.print("Enter your first and last name separated by a space: ");
first = stdIn.next();
last = stdIn.next();
File file = new File("Output.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
output.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
If you havent already, have a look into Java Basic Syntax
and the docs of PrintWriter to check what exceptions are thrown by what method so you can either catch them and handle them like i did above, or just pass them on.
Also, using an IDE such as eclipse, will show you all syntax errors real-time as you code so you dont have to compile every time yourself to check if your syntax is correct. Also most IDE's often come with sugested solutions for perticular errors. Other than this, it will warn you about what method throws what exception so you can catch them.
try this
BufferedWriter br= new BufferedWriter(new FileWriter(file)){
br.write(first + " " + last);
}
I want to be able to remove blank lines from a text file, for example:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
--To This:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
All of the code I have is below:
public class Driver {
public static void main(String[] args)
throws Exception {
Scanner file = new Scanner(new File("src/data.txt"));
PrintWriter write = new PrintWriter("src/data.txt");
while(file.hasNext()) {
if (file.next().equals("")) {
continue;
} else {
write.write(file.next());
}
}
print.close();
file.close();
}
}
The problem is that the text file is empty once I go back and look at the file again.
Im not sure why this is acting this way since they all seem to be blank characters, \n showing line breaks
Your code was almost correct, but there were a few bugs:
You must use .nextLine() instead of .next()
You must write to a different file while reading the original one
Your print.close(); should be write.close();
You forgot to add a new line after each line written
You don't need the continue; instruction, since it's redundant.
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to keep the original name, you can do something like:
File file1 = new File("src/data.txt");
File file2 = new File("src/data2.txt");
file1.delete();
file2.renameTo(file1);
Try org.apache.commons.io and Iterator
try
{
String name = "src/data.txt";
List<String> lines = FileUtils.readLines(new File(name));
Iterator<String> i = lines.iterator();
while (i.hasNext())
{
String line = i.next();
if (line.trim().isEmpty())
i.remove();
}
FileUtils.writeLines(new File(name), lines);
}
catch (IOException e)
{
e.printStackTrace();
}
You could copy to a temporary file and rename it.
String name = "src/data.txt";
try(BufferedWriter bw = new BufferedWriter(name+".tmp)) {
Files.lines(Paths.get(name))
.filter(v -> !v.trim().isEmpty())
.forEach(bw::println);
}
new File(name+".tmp").renameTo(new File(name));
This piece of code solved this problem for me
package linedeleter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class LineDeleter {
public static void main(String[] args) throws FileNotFoundException, IOException {
File oldFile = new File("src/data.txt"); //Declares file variable for location of file
Scanner deleter = new Scanner(oldFile); //Delcares scanner to read file
String nonBlankData = ""; //Empty string to store nonblankdata
while (deleter.hasNextLine()) { //while there are still lines to be read
String currentLine = deleter.nextLine(); //Scanner gets the currentline, stories it as a string
if (!currentLine.isBlank()) { //If the line isn't blank
nonBlankData += currentLine + System.lineSeparator(); //adds it to nonblankdata
}
}
PrintWriter writer = new PrintWriter(new FileWriter("src/data.txt"));
//PrintWriter and FileWriter are declared,
//this part of the code is when the updated file is made,
//so it should always be at the end when the other parts of the
//program have finished reading the file
writer.print(nonBlankData); //print the nonBlankData to the file
writer.close(); //Close the writer
}
}
As mentioned in the comments, of the code block, your sample had the print writer declared after your scanner meaning that the program had already overwritten your current file of the same name. Therefore there was no code for your scanner to read and thus, the program gave you a blank file
the
System.lineSeparator()
Just adds an extra space, this doesn't stop the program from continuing to write on that space, however, so it's all good
The program that I am trying to create is a program that takes words from a user defined file, saves those words as variables and then searches a different user defined file for those words, outputting there location.
The program works up to and including the point where the program takes the words and saves them as variables. The problem with the program is that the search method returns a null result. My main suspicions are that the code in the search method is incompatible with the code in the read method, or that the 2 methods aren't running simultaneously.
The search method is in the searching class and the read method is in the reading class.
Here is my code (Containing all 3 of my classes), please excuse all of the imports.
This is the first class:
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Combination{
public static void main(String[] args) throws FileNotFoundException{
Scanner userInput = new Scanner(System.in);
Reading ReadingObject = new Reading();
System.out.println("Please enter the file that you wish to open");
String temp = userInput.nextLine();
ReadingObject.setFileName(temp);
ReadingObject.read();
Scanner searchForWord = new Scanner(System.in);
Searching SearchingObject = new Searching();
System.out.println("Please enter the file that you would like to search for these words in");
String temp1 = searchForWord.nextLine();
SearchingObject.setFileName(temp1);
SearchingObject.search();
}
}
This is the second class:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
class Reading {
private String file;
public void setFileName(String fileName){
file = fileName;
}
public String getFileName(){
return file;
}
public void read(){
try{
//Choosing the file to open
FileInputStream fstream = new FileInputStream(getFileName());
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
//Read the file line by line
while((strLine = br.readLine()) != null){
// \\s+ means any number of whitespaces between tokens
String [] tokens = strLine.split("\\s+");
String [] words = tokens;
for(String word : words){
System.out.print(word);
System.out.print(" ");
Searching SearchingObject = new Searching();
SearchingObject.setWord(word);
}
System.out.print("\n");
}
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
This is the third class:
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Searching {
private String file1;
public void setFileName(String fileName){
file1 = fileName;
}
public String getFileName(){
return file1;
}
private String word1;
public void setWord(String wordName){
word1 = wordName;
}
public String getWord(){
return word1;
}
public void search() throws FileNotFoundException{
try{
//Choosing the file to open
FileInputStream fstream = new FileInputStream(getFileName());
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
while((strLine = br.readLine()) != null){
Pattern p = Pattern.compile(getWord());
Matcher m = p.matcher(strLine);
int start = 0;
while (m.find(start)) {
System.out.printf("Word found: %s at index %d to %d.%n", m.group(), m.start(), m.end());
start = m.end();
}
}
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Any help will be greatly appreciated.
Regards
Your code is hard to read. Your reading class does not only read; it also searches. You should call it something that reflects its intended use. However, it forgets to tell its searching object where to search, and does not pass the reference to this object to anyone else. In this snippet
for (String word : words) {
System.out.print(word);
System.out.print(" ");
searching searchingObject = new searching();
searchingObject.setWord(word);
}
you are essentially not doing anything. The reference to searchingObject is lost forever.
Your reading class should keep an ArrayList of words to be searched for in the searching, instead of instancing searching objects.
Your searching class should take, as a constructor parameter, one of these ArrayLists -- and convert it into a single regex, which is much more efficient than reading the file once per word to search for. You can search for "a", "b" and "c" using the single regular expression "a|b|c". Works with longer words, too. Escape them first to avoid problems.
Oh, and please, please follow naming guidelines. Call your reading a TokenReader, and your searching a WordListSearcher...