Im trying to create an application that reads names from an input file and writes the number of duplicate names on an output file. Heres my code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
public class GenerateDuplicateBookTitle {
public static void main(String[] args) {
// declare and intialize path where the input file is stored
String filePath = "C:/Users/User/OneDrive/Desktop/JavaProgram";
// intialize input file name and output file name
String inputFile = "bookTitles.inp";
String ouputFile = "duplicateTitles.inp";
// create HashSet which does not store duplicate values
HashSet<String> bookTitles = new HashSet<>();
// create arrayList which stores only duplicate bok titles
ArrayList<String> duplicateBookTitles = new ArrayList<>();
// now read the book titles from the bookTitles.inp
try{
// create an object Of fileReader class with the specified filename with the path
FileReader fr = new FileReader(filePath+inputFile);
// create an object of BufferedReader class for reading line from inp file
BufferedReader br = new BufferedReader(fr);
String getLine = "";
System.out.println("-------------- Fetch data from the file ---------------\n");
while((getLine = br.readLine()) != null){
// add book title to the bookTitles arrayList
if(!bookTitles.contains(getLine)){
// diplay to the console
System.out.println(getLine+" read successfully from "+filePath+inputFile);
// add to the hash set
bookTitles.add(getLine);
}else{
duplicateBookTitles.add(getLine);
}
}
// display duplicate book title into the console
System.out.print("Duplicate book titles fetched from "+filePath+inputFile+" : ");
System.out.println(duplicateBookTitles.toString());
// now store it into the "duplicateTitles.txt" file
// create an object of FIleWriter class for writing data into the txt file
FileWriter write = new FileWriter(filePath+ouputFile);
System.out.println("\n------------ Write Duplicate BookTitles ----------------\n");
// now get each element from the duplicateBookTitles arrayList
for(String duplicateBookTitle : duplicateBookTitles){
// write into the "duplicateTitles.txt" file
write.write(duplicateBookTitle+"\n");
// print on console
System.out.println(duplicateBookTitle+" write succssfully into the
"+filePath+ouputFile);
}
// close the writer
write.close();
fr.close();
br.close();
}catch(FileNotFoundException e){
System.out.println("FILE '"+inputFile+"' IS NOT FOUND in "+filePath);
} catch (IOException ex) {
System.out.println(ex);
}
}
I keep getting an error message that the input file can't be found even though I am typing in the exact address of the file. The file name and format are correct and its in the same folder as the BlueJ program. What am I doing wrong here?
You are concatenating the directory path and the filename without the "/". Change FileReader fr = new FileReader(filePath+inputFile); to:
FileReader fr = new FileReader(filePath + "/" + inputFile);
Alternatively, you can do:
FileReader fr = new FileReader(new File(filePath, inputFile));
Related
I want a user to be able to copy and paste multi-line text into the console and then save it to a specific text file ("weather.text" in this case which is located in a data folder within the same package). I've been working on this simple task for a few hours and the solution is evading me. I'm new to java so I apologize in advance.
This static function is called from the main launcher class.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Scanner;
public static void writeFile()
{
//set up for the user input
Reader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
String str = null;
try {
//prompt the user to input data
System.out.println("Type or paste your data and hit Ctrl + z");
str = br.readLine();
//save the user input data to text file
PrintWriter writer = new PrintWriter("weather.txt", "UTF-8");
writer.print(str);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
currently I'm experiencing 2 problems.
1) The code above seems to only save the first line pasted into the console into the console.
2) The text file being saved is in the global project folder and not the specified data sub folder.
Any help or suggestions are appreciated. Thank you.
You are writing str, but str is just the first line in br You have to read all lines in a loop.
Try this code:
public static void writeFile()
{
//set up for the user input
Reader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
String str = null;
try {
//prompt the user to input data
System.out.println("Type or paste your data and hit Ctrl + z");
PrintWriter writer = new PrintWriter("weather.txt", "UTF-8");
while((str = br.readLine())!=null)
{
//save the line
writer.println(str);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
about the second issue, the file is written in the working directory of your application.
I need to make a system for storing customer information and all quotations to an external file as well as entering more customers, listing customers, and the same with the quotations. As well as this I need to link all quotations/customers to an ID. I basically need to do SQL in java. However, I really need help with my input and output system, and writing all info to an array. I have got two main pieces of code but they are very inefficient and I need some suggestions, improvements or an entirely different system.
Input from file Code:
import java.io.*; //import classes
import java.util.ArrayList;
import java.util.Iterator;
public class MyTextReader{
public static void main(String[] args){
String myDirectory = System.getProperty("user.dir");
String fullDirectory = myDirectory + "\\myText.txt";
String input_line = null;
ArrayList<String> textItems = new ArrayList<String>(); //create array list
try{
BufferedReader re = new BufferedReader(new FileReader(fullDirectory));
while((input_line = re.readLine()) != null){
textItems.add(input_line); //add item to array list
}
}catch(Exception ex){
System.out.println("Error: " + ex);
}
Iterator myIteration = textItems.iterator(); //use Iterator to cycle list
while(myIteration.hasNext()){ //while items exist
System.out.println(myIteration.next()); //print item to command-line
}
}
}
Output to File
import java.io.FileWriter; //import classes
import java.io.PrintWriter;
public class MyTextWriter{
public static void main(String[] args){
FileWriter writeObj; //declare variables (uninstantiated)
PrintWriter printObj;
String myText = "Hello Text file";
try{ //risky behaviour – catch any errors
writeObj = new FileWriter("C:\\Documents\\myText.txt" , true);
printObj = new PrintWriter(writeObj);//create both objects
printObj.println(myText); //print to file
printObj.close(); //close stream
}catch(Exception ex){
System.out.println("Error: " + ex);
}
}
}
For reading text from a file
FileReader fr = new FileReader("YourFile.txt");
BufferedReader br = new BufferedReader(fr);
String s="";
s=br.readLine();
System.out.println(s);
For Writting Text to file
PrintWriter writeText = new PrintWriter("YourFile.txt", "UTF-8");
writeText.println("The first line");
writeText.println("The second line");
writeText.close();
I am trying to add objects to a queue from a data file which is made up of text which is made up of a person's first name and their 6 quiz grades (ie: Jimmy,100,100,100,100,100,100). I am accessing the data file using the FileReader and using BufferReader to read each line of my data file and then tokenize each line using the "," deliminator to divide the names and quiz grades up. Based on what I think my professor is asking for is to create a queue object for each student. The assignment says,
Read the contents of the text file one line at a time using a loop. In this loop, invoke the processInputData method for each line read. This method returns the corresponding Student object. Add this student object to the studentQueue.
If someone could point me the right direction that would be great! Here is my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
// Create an empty queue of student objects
LinkedList<Student> studentQueue;
studentQueue = new LinkedList<Student>();
// Create an empty map of Student objects
HashMap<String, Student> studentMap = new HashMap<String, Student>();
System.out.printf("Initial size = %d\n", studentMap.size());
// Open and read text file
String inputFileName = "data.txt";
FileReader fileReader = null;
// Create the FileReader object
try {
fileReader = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// BufferReader to read text file
BufferedReader reader = new BufferedReader(fileReader);
String input;
// Read one line at a time until end of file
try {
input = reader.readLine();
while (input != null) {
processInputData(input);
input = reader.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
// Close the input
try {
fileReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
// Tokenize the data using the "," as a delimiter
private static void processInputData(String data) {
StringTokenizer st = new StringTokenizer(data, ",");
String name = st.nextToken();
String homework1 = st.nextToken();
String homework2 = st.nextToken();
String homework3 = st.nextToken();
String homework4 = st.nextToken();
String homework5 = st.nextToken();
String homework6 = st.nextToken();
// Using the set methods to correspond to the Student object
Student currentStudent = new Student(name);
currentStudent.setHomework1(Integer.parseInt(homework1));
currentStudent.setHomework2(Integer.parseInt(homework2));
currentStudent.setHomework3(Integer.parseInt(homework3));
currentStudent.setHomework4(Integer.parseInt(homework4));
currentStudent.setHomework5(Integer.parseInt(homework5));
currentStudent.setHomework6(Integer.parseInt(homework6));
System.out.println("Input File Processing...");
System.out.println(currentStudent);
}
}
One possible solution to your problem is returning the student in processInputData(..)
private static Student processInputData(String data) {
// the same code
return currentStudent;
}
And in while loop
while (input != null) {
studentQueue.add(processInputData(input));
input = reader.readLine();
}
Also try to manage better your try-catch blocks, cause if your fileReader throws exception then the code will continue running and throw probably a nullPointerException that you don't handle.
try{
fileReader = new FileReader(inputFileName);
BufferedReader reader = new BufferedReader(fileReader);
}catch(IOException ex){
//handle exception;
}finally{
// close resources
}
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Cities {
public static void main(String[] args) throws IOException {
String filename;
System.out.println("Enter the file name : ");
Scanner kb = new Scanner(System.in);
filename = kb.next();
//Check if file exists
File f = new File(filename);
if(f.exists()){
//Read file
File myFile = new File(filename);
Scanner inputFile = new Scanner(myFile);
//Create arraylist object
ArrayList<String> list = new ArrayList<String>();
String cit;
while(inputFile.hasNext()){
cit = inputFile.toString();
list.add(inputFile.toString());
}
System.out.println(list);
}else{
System.out.println("File not found!");
}
}
}
I am trying to read a file and add the contents to an arraylist object (.txt file contains strings), but I am totally lost. Any advice?
You should read the file one line by one line and store it to the list.
Here is the code you should replace your while (inputFile.hasNext()):
Scanner input = null;
try
{
ArrayList<String> list = new ArrayList<String>();
input = new Scanner( new File("") );
while ( input.hasNext() )
list.add( input.nextLine() );
}
finally
{
if ( input != null )
input.close();
}
And you should close the Scanner after reading the file.
If you're using Java 7+, then you can use the Files#readAllLines() to do this task for you, instead of you writing a for or a while loop yourself to read the file line-by-line.
File f = new File(filename); // The file from which input is to be read.
ArrayList<String> list = null; // the list into which the lines are to be read
try {
list = Files.readAllLines(f.toPath(), Charset.defaultCharset());
} catch (IOException e) {
// Error, do something
}
You can do it in one single line with Guava.
final List<String> lines = Files.readLines(new File("path"), Charsets.UTF8);
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#readLines(java.io.File, java.nio.charset.Charset)
im studying for my programming final exam. I have to write a program which opens a file which is stored in the string fileName and look in the file for a String called personName and this should print the first string after personName then the program should terminate after printing it,
if the argument personName is not in the file then it should print "this name doen't exsit" then if an IOException occurs it should then print "there is an IO Error" and the program should exsit using system.exit(0)
the program should use the file info.txt and each line should contain two strings
first string name and second age.
everything must be in one method
data.txt contains
Max 60.0
joe 19.0
ali 20.0
my code for this so far is :
public class Files{
public void InfoReader(String fileName, String personName)
{
try{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C://rest//data.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
while ((fileName = br.readLine()) != null) {
// Print the content on the console
(new Files()).infoReader("info.txt","Joe"); //this prints the age
}
//Close the input stream
in.close();
}
catch (IOException e)
{//Catch exception if any
System.out.println(" there is an IO Error");
System.exit(0);
}
}
catch (Exception e)
{//Catch exception if any
System.out.println("that name doesn't exists");
}
}
}
infoReader(info.txt,Joe); should print 19.0
But I am getting a java.lang.StackOverflowError
any help would be much appreciated!!
Thanks in advance!
This is what I think you are trying to do. And if doesn't, at least can work as an example. Just as amit mentions, your current error is because of the recursive call, which I think is not necessary.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Files {
public void InfoReader(String fileName, String personName) {
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
//Loop until there are no more lines in the file
while((line = br.readLine()) != null) {
//Split the line to get 'personaName' and 'age'.
String[] lineParts = line.split(" ");
//Compare this line personName with the one provided
if(lineParts[0].equals(personName)) {
//Print age
System.out.println(lineParts[1]);
br.close();
System.exit(0);
}
}
br.close();
//If we got here, it means that personName was not found in the file.
System.out.println("that name doesn't exists");
} catch (IOException e) {
System.out.println(" there is an IO Error");
}
}
}
If you use the Scanner class, it would make your life so much easier.
Scanner fileScanner = new Scanner (new File(fileName));
while(fileScanner.hasNextLine()
{
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
String name = lineScanner.next(); // gets the name
double age = Double.parseDouble(lineScanner.next()); // gets the age
// That's all really! Now do the rest!
}
Use commons-io and dont forget the encoding!
List<String> lines = FileUtils.readLines(file, encoding)