My assignment is as following Create Java program that reads from file create one person Object per line and stores object in a collection write the object out sorted by last name. this is what I have so far it compiles just fine but it doesn't print out anything. This is what I have so far
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileTester {
public static void main(String[] args) {
File testFile;
Scanner fileScanner;
try {
testFile = new File("sample.txt");
fileScanner = new Scanner(testFile);
fileScanner.useDelimiter(",");
while (fileScanner.hasNext()) {
System.out.println(fileScanner.next());
}
fileScanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
If it is a text file, please use BufferedReader. Then use String#split() to get the data. Instantiate as necessary.
BufferedReader reader = new BufferedReader(...);
String line = null;
while( (line = reader.readLine()) != null){
// magic
}
I do not know what you want to do. But this program take a file called "sample.txt" and divide in tokens this. For example if in the txt is "carlos,jose,herrera,matos" you program out
carlos
jose
herrera
matos
now if you want to sort this, you must create a class Person and implement the Comparable
Try this,
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(fileName)));
String content = null;
while((content = bufferedReader.readLine()) != null)
{
String[] details = content.split(",");
int i = 1;
for(String value : details)
{
switch(i)
{
case 1:
{
System.out.println("Name : "+value);
i=2;
break;
}
case 2:
{
System.out.println("Address : "+value);
i=3;
break;
}
case 3:
{
System.out.println("Number : "+value);
i = 1;
break;
}
}
}
}
Related
I've been searching the web and I can't seem to find a working solution.
I have a file containing theses lines:
Room 1
Coffee
Iron
Microwave
Room_end
Room 2
Coffee
Iron
Room_end
I want to print all Strings between Room 1 and Room_end. I want my code to start when it find Room 1, print line after Room 1 and stop when it get to the first Room_end it find.
private static String LoadRoom(String fileName) {
List<String> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
result = reader.lines()
.dropWhile(line -> !line.equals("Room 1"))
.skip(1)
.takeWhile(line -> !line.equals("Room_end"))
.collect(Collectors.toList());
} catch (IOException ie) {
System.out.println("Unable to create " + fileName + ": " + ie.getMessage());
ie.printStackTrace();
}
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i).getname());//error on getname because it cant work with Strings
}
}
class Model {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I am able to get a method to print all Strings of the file but not specific range of Strings. I also tried to work with Stream. My code feel quite messy, but I've been working on it for a while an it seems it only get messier.
I think there is a problem if you want to use lambda expression here:
lambda expressions are functional programming, and functional programming requires immutability, that means there should not be state related issue, you can call the function and give it same parameters and the result always will be the same, but in your case, there should be a state indicating whether you should print the line or not.
can you try this solution? I write it in python, but mainly it is just about a variable should_print that located outside of the scope
should_print = False
result = reader.lines()
for line in result:
if line == "Room end":
break
if should_print:
print(line)
if line == "Room 1":
should_print = True
keep a boolean value outside of the iteration, and check/update the value in each iteration
public static Map<String, List<String>> getRooms(String path) throws IOException {
Map<String, List<String>> result = new HashMap<>();
try (Scanner sc = new Scanner(new File(path))) {
sc.useDelimiter("(?=Room \\d+)|Room_end");
while (sc.hasNext()) {
Scanner lines = new Scanner(sc.next());
String room = lines.nextLine().trim();
List<String> roomFeatures = new ArrayList<>();
while (lines.hasNextLine()) {
roomFeatures.add(lines.nextLine());
}
if (room.length() > 0) {
result.put(room, roomFeatures);
}
}
}
return result;
}
is one way of doing it for your 'rooms file' though it should really be made more OO by making a Room bean to hold the data. Output with your file: {Room 2=[Coffee, Iron ], Room 1=[Coffee, Iron, Microwave]}
Switched my code and used this:
private static String loadRoom(String fileName) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null; //we start with empty info
String ls = System.getProperty("line.separator"); //make a new line
while ((line = reader.readLine()) != null) { //consider if the line is empty or not
if (line.equals("Room 1")) { //condition start on the first line being "Room 1"
line = reader.readLine(); // read the next line, "Room 1" not added to stringBuilder
while (!line.equals("Room_end")) { //check if line String is "Room_end"
stringBuilder.append(line);//add line to stringBuilder
stringBuilder.append(ls);//Change Line in stringBuilder
line = reader.readLine();// read next line
}
}
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
Here's a solution that uses a scanner and a flag. You may choose to break the loop when it reads "Room_end"
import java.util.Scanner;
import java.io.*;
public class Main{
private static String loadRoom(String fileName) throws IOException {
Scanner s = new Scanner(new File(fileName));
StringBuilder sb = new StringBuilder();
boolean print = false;
while(s.hasNextLine()){
String line = s.nextLine();
if (line.equals("Room 1")) print = true;
else if (line.equals("Room_end")) print = false;
else if (print) sb.append(line).append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
try {
String content = loadRoom("content.txt");
System.out.println(content);
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
I'm trying to write my java console output to a .txt file in my desktop.
But when that method starts, i have the console output and the txt file gets created, but it's empty and I realized that the BufferedReader (in) is not working... (Because of the "ok1 - i" statement)
The question is WHY?? or WHAT'S WRONG WITH MY CODE??
This is my code, so you can see and run it
package noobxd;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class Main {
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\Mario\\Desktop\\output.txt";
generate_codes();
writetxt(path);
}
private static void writetxt(String path) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter(path));
try {
String inputLine;
inputLine = "";
int i=0;
System.out.println("Starting");
while (!inputLine.isEmpty()){
System.out.println("ok1"+i);
inputLine = in.readLine();
System.out.println("ok2"+i);
out.write(inputLine);
System.out.println("ok3"+i);
out.newLine();
System.out.println("ok4"+i);
i++;
}
System.out.print("Write Successful");
} catch (IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
private static void generate_codes() {
Random rnd = new Random();
for (int i = 0; i < 30; i++) {
int code = rnd.nextInt(201) + 100;
int students = rnd.nextInt(31) + 40;
int j = rnd.nextInt(4);
String type = new String();
switch (j) {
case 0:
type = "Theory";
break;
case 1:
type = "Lab";
break;
case 2:
type = "Practice";
break;
case 3:
type = "Exam";
break;
}
System.out.println("TEL" + code + "-TopicNumber" + i + "-" + students + "-" + type);
}
}
}
Thanks for your time, please help me solve my problem.
String inputLine;
inputLine = "";
...
while (!inputLine.isEmpty()) // this is false and so the loop is not executed
In the future, please learn to use debugging tools and simply read your code more carefully. If you're trying to read until EOF, use
while ((inputLine = in.readLine()) != null) {
...
}
If you want to keep looping until the user enters an empty line at the console, you probably want something like
while (true) {
System.out.println("ok1"+i);
inputLine = in.readLine();
if (inputLine.isEmpty())
break;
// the rest of your loop
}
You probable should do something like this:
inputLine = in.readLine();
while (inputLine != null && !inputLine.isEmpty()){
System.out.println("ok1"+i);
System.out.println("ok2"+i);
out.write(inputLine);
System.out.println("ok3"+i);
out.newLine();
System.out.println("ok4"+i);
i++;
inputLine = in.readLine();
}
I have a file that contain 100 line
each line contain one tag
I need to obtain the tag value given its rank which is the "id" of TagVertex Class
public abstract class Vertex <T>{
String vertexId ;// example Tag1
T vertexValue ;
public abstract T computeVertexValue();
}
public class TagVertex extends Vertex<String> {
#Override
public String computeVertexValue() {
// How to get the String from my file?
return null;
}
T try this but it doesnt work
public static void main(String args[]) {
File source //
int i=90;
int j=0;
String s = null;
try {
Scanner scanner = new Scanner(source);
while (scanner.hasNextLine()) {
if (j==i) s= scanner.nextLine();
else j++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(s);
}}
Although there is a way to skip characters with BufferedReader, I don't think there's is a built-in way to skip whole lines.
BufferedReader bf = new BufferedReader(new FileReader("MyFile.txt"));
for(int i = 1; i < myVertex.vertexId; i++){
bf.readLine();
}
String n = bf.readLine();
if(n != null){
System.out.println(n);
}
I think there may be a better idea though.
This is command u can use to read from file:
BufferedReader bf = new BufferedReader(new FileReader("filename"));
This will read the file to the buffer.
Now, for reading each line u should use a while loop and read each line into string.
Like:
String str;
while((str = bf.readLine()) != null){
//handle each line untill the end of file which will be null and quit the loop
}
I'm looking to sort the contacts read from a file in alphabetical order by last name to the console? How would I go about doing so? The contacts are already written to file starting with the last name, I just want to read them back into the application in alphabetical order when a user wants to view the contacts in the console.
// Read from file, print to console. by XXXXX
// ----------------------------------------------------------
int counter = 0;
String line = null;
// Location of file to read
File file = new File("contactlist.csv");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
counter++;
}
scanner.close();
} catch (FileNotFoundException e) {
}
System.out.println("\n" + counter + " contacts in records.");
}
break;
// ----------------------------------------------------------
// End read file to console. by XXXX
Before printing, add each line to a sorted set, as a TreeSet:
Set<String> lines = new TreeSet<>();
while (scanner.hasNextLine()) {
line = scanner.nextLine();
lines.add(line);
counter++;
}
for (String fileLine : lines) {
System.out.println(fileLine);
}
package main.java.com.example;
import java.io.*;
import java.net.URL;
import java.util.Set;
import java.util.TreeSet;
public class ReadFromCSV {
public static void main(String[] args) {
try {
final ClassLoader loader = ReadFromCSV.class.getClassLoader();
URL url = loader.getResource("csv/contacts.csv");
if (null != url) {
File f = new File(url.getPath());
BufferedReader br = new BufferedReader(new FileReader(f));
Set<String> set = new TreeSet<String>();
String str;
while ((str = br.readLine()) != null) {
set.add(str);
}
for (String key : set) {
System.out.println(key);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read names from the file, put them in an object of class SortedSet.
So this is what I have so far :
public String[] findStudentInfo(String studentNumber) {
Student student = new Student();
Scanner scanner = new Scanner("Student.txt");
// Find the line that contains student Id
// If not found keep on going through the file
// If it finds it stop
// Call parseStudentInfoFromLine get the number of courses
// Create an array (lines) of size of the number of courses plus one
// assign the line that the student Id was found to the first index value of the array
//assign each next line to the following index of the array up to the amount of classes - 1
// return string array
}
I know how to find if a file contains the string I am trying to find but I don't know how to retrieve the whole line that its in.
This is my first time posting so If I have done anything wrong please let me know.
You can do something like this:
File file = new File("Student.txt");
try {
Scanner scanner = new Scanner(file);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if(<some condition is met for the line>) {
System.out.println("ho hum, i found it on line " +lineNum);
}
}
} catch(FileNotFoundException e) {
//handle this
}
Using the Apache Commons IO API https://commons.apache.org/proper/commons-io/ I was able to establish this using FileUtils.readFileToString(file).contains(stringToFind)
The documentation for this function is at https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?
Scanner scanner = new Scanner("Student.txt");
String currentLine;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Perform logic
}
}
You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:
Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Do task
passedLine = true;
}
if(passedLine)
{
//Do other task after passing the line.
}
lineNumber++;
}
This will find "Mark Sagal" in Student.txt. Assuming Student.txt contains
Student.txt
Amir Amiri
Mark Sagal
Juan Delacruz
Main.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
final String file = "Student.txt";
String line = null;
ArrayList<String> fileContents = new ArrayList<>();
try {
FileReader fReader = new FileReader(file);
BufferedReader fileBuff = new BufferedReader(fReader);
while ((line = fileBuff.readLine()) != null) {
fileContents.add(line);
}
fileBuff.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents.contains("Mark Sagal"));
}
}
I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.
This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
//Add the path to the list of file paths
textFilePaths.push_back(path);
int lineNumber = 1;
while(!txtFile.eof())
{
txtFile.getline(line, 200);
Line * ln = new Line(line, path, lineNumber);
lineNumber++;
myList.push_back(ln);
vector<string> words = lineParser(ln);
for(unsigned int i = 0; i < words.size(); i++)
{
index->addWord(words[i], ln);
}
}
result = true;
}
Here is the code of TextScanner
public class TextScanner {
private static void readFile(String fileName) {
try {
File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java TextScanner1"
+ "file location");
System.exit(0);
}
readFile(args[0]);
}
}
It will print text with delimeters