How can I implement a method to return the line-number of the line currently being scanned from a file. I have two scanners, one for the file (fileScanner) and another for the line (lineScanner)
this is what I have, but I don't know if I need the linenumber in the constructor!
public TextFileScanner(String fileName) throws FileNotFoundException
{
this.fileScanner = new Scanner(new File(fileName));
this.lineScanner = new Scanner(this.fileScanner.nextLine());
this.lineNumber = 1;
}
and I need this method:
public int getLineNumber()
{
}
You can use just one Scanner object to read a file and reports the line numbers.
Here is a sample code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LineNumber {
public static void main(String [] args) throws FileNotFoundException {
System.out.printf("Test!\n");
File f = new File("test.txt");
Scanner fileScanner = new Scanner(f);
int lineNumber = 0;
while(fileScanner.hasNextLine()){
System.out.println(fileScanner.nextLine());
lineNumber++;
}
fileScanner.close();
System.out.printf("%d lines\n", lineNumber);
}
}
Now, if you want do this using an Object-Oriented Programming approach then you can do something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileProcessor {
// Mark these field as private so the object won't get tainted from outside
private String fileName;
private File file;
/**
* Instantiates an object from the FileProcessor class
*
* #param fileName
*/
public FileProcessor(String fileName) {
this.fileName = fileName;
this.file = new File(fileName);
}
public int getLineNumbers() {
Scanner fileScanner = null;
try {
fileScanner = new Scanner(this.file);
} catch (FileNotFoundException e) {
System.out.printf("The file %s could not be found.\n",
this.file.getName());
}
int lines = 0;
while (fileScanner.hasNextLine()) {
lines++;
// Go to next line in file
fileScanner.nextLine();
}
fileScanner.close();
return lines;
}
/**
* Test our FileProcessor Class
*
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
FileProcessor fileProcessor = new FileProcessor("text.txt");
System.out.printf("%d lines\n", fileProcessor.getLineNumbers());
}
}
Prints the Current line number:
System.out.println("The line number is " + new Exception().getStackTrace()[0].getLineNumber());
Example:
public class LineNumberTest{
public static void main(String []args){
System.out.println("The line number is " + new Exception().getStackTrace()[0].getLineNumber());
}
}
Related
I'm trying to read a text file and store it in an arraylist of objects, but I keep getting an error saying I cannot convert a String to an Item, which is type of arraylist I am using. I have tried various solutions, but am not quite sure how its is suppossed to be done. I am new to coding and have this assignment due soon. Anything helps!
private void loadFile(String FileName)
{
Scanner in;
Item line;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
line = in.nextLine();
MyStore.add(line);
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
my apologies for not adding the Item class
public class Item
{
private int myId;
private int myInv;
//default constructor
public Item()
{
myId = 0;
myInv = 0;
}
//"normal" constructor
public Item(int id, int inv)
{
myId = id;
myInv = inv;
}
//copy constructor
public Item(Item OtherItem)
{
myId = OtherItem.getId();
myInv = OtherItem.getInv();
}
public int getId()
{
return myId;
}
public int getInv()
{
return myInv;
}
public int compareTo(Item Other)
{
int compare = 0;
if (myId > Other.getId())
{
compare = 1;
}
else if (myId < Other.getId())
{
compare = -1;
}
return compare;
}
public boolean equals(Item Other)
{
boolean equal = false;
if (myId == Other.getId())
{
equal = true;;
}
return equal;
}
public String toString()
{
String Result;
Result = String.format("%8d%8d", myId, myInv);
return Result;
}
}
This is the creation of my arraylist.
private ArrayList MyStore = new ArrayList ();
Here is a sample of my text file.
3679 87
196 60
12490 12
18618 14
2370 65
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.rosmery;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author Sem-6-INGENIERIAINDU
*/
public class aaa {
public static void main(String arg[]) throws FileNotFoundException, IOException{
BufferedReader files=new BufferedReader(new FileReader(new File("")));
List<String> dto=new ArrayList<>();
String line;
while((line= files.readLine())!= null){
line= files.readLine();
dto.add(line);
//Hacer la logica para esos datos
}
}
}
in.nextLine() returns a String.
So, you cannot assign in.nextLine() to an instance of Item.
Your code may need to correct it as:
List<String> myStore = new ArrayList<String>();
private void loadFile(String FileName)
{
Scanner in;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
myStore.add(in.nextLine());
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
If you want to have a list of Item after reading a file, then you need provide the logic that convert given line of information into an instance of Item.
let's say your file content is in the following format.
id1,inv1
id2,inv2
.
.
Then, you can use the type Item as the following.
List<Item> myStore = new ArrayList<Item>();
private void loadFile(String FileName)
{
Scanner in;
String[] line;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
line = in.nextLine().split(",");
myStore.add(new Item(line[0], line[1]));
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
One of the possible solutions (assuming that the data in file lines is separated by a comma), with using streams:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
List<Item> items = loadFile("myfile.txt");
System.out.println(items);
}
private static List<Item> loadFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream
.map(s -> Stream.of(s.split(",")).mapToInt(Integer::parseInt).toArray())
.map(i -> new Item(i[0], i[1]))
.collect(Collectors.toList());
}
}
}
or with foreach:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
List<Item> items = new ArrayList<>();
for (String line : loadFile("myfile.txt")) {
String[] data = line.split(",");
int id = Integer.parseInt(data[0]);
int inv = Integer.parseInt(data[1]);
items.add(new Item(id, inv));
}
System.out.println(items);
}
private static List<String> loadFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream.collect(Collectors.toList());
}
}
}
So I have this code where it prompts the user to type in a file name for the input file and the file name for the output file. I have a string called 'names' which will then be stored into the input file that was created by the user. I've got this part down.
import com.sun.org.apache.xpath.internal.SourceTree;
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter(chooseFile("input"));
FileWriter writer2 = new FileWriter(chooseFile("output"));
String separator = String.format("%n");
for(String name: names){
writer.write(name);
writer.write(separator);
}
}
}
public static File chooseFile(String type) {
String fname = null;
}
return file;
}
}
Something like so should modify your names list to all caps.
for (int i = 0; i < names.length; i++) {
names[i] = names[i].toUpperCase();
// writer2.write(names[i]);
}
I have this written so far, I am just doing a few practice codes from my text book. I cant seem to get this to read the first line in my .txt .
/**
*
*/
import java.util.Scanner; //needed for scanner class
import java.io.*; //needed for File I/O classes
/**
* #author Megan
*
*/
public class Pres {
/**
* #param args
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of file: C:/User/Frances/Documents/USPres.txt");
String filename = keyboard.nextLine();
File file = new File("C:/User/Frances/Documents/USPres.txt");
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
System.out.println("The first line in the file is: ");
System.out.println(line);
inputFile.close();
}
}
I believe it has to do with this portion of the code:
String line = inputFile.nextLine();
I am not quite sure what to type into the (), if I should type anything at all. I could be wrong. My textbook isn't to clear about the proper format. If you could help, please and thank you. :)
To read txt file do this:
String line = "";
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(fileName));
while ((line = in.readLine()) != null) {
// do something here
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It will read all lines in the text but since it's practice go ahead and try to figure out how to read just one line.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Pres {
public static void main(String[] args) throws FileNotFoundException, IOException {
// BufferedReader is best for read line from file or else
BufferedReader Bfr = new BufferedReader(new FileReader("your_filename_or_path.txt"));
// get first line from file
String firstLinetext = Bfr .readLine();
System.out.println(firstLinetext ); // print first line
}
}
What I want to do: My class copytest reads a textfile, edits one character and save this new file in a new directory. I want to program a void-method out of it, which does exactly the same and can then be used the following way:
copy(String "C:\\Old.txt", String "C:\\New.txt", int 1, int 1)
Now copy does exactly the same as my old class copytest, it reads the old file, edits it and saves it.
My first idea was to have two files as the first to arguments, but this is obviously impossible. My new idea is to give the method two strings of the wanted directories of the old and the new file. It still doesn't work. I hope, you understand, what I want to do and how to solve this problem.
Old class code (works):
import java.io.*;
import java.util.Scanner;
public class copytest {
public static void main(String[] args) throws Exception {
readFile();
}
public static void readFile() throws Exception {
// Location of file to read
File file = new File("...old.txt");
Scanner scanner = new Scanner(file);
int lineNumber=1;
int charNumber=1;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File("...new.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
}
New void code (first try with file as argument):
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
Scanner scanner = new Scanner(old);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File(new.getPath());
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
readFile();
}
New try with strings as argument, but still doesn't work:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class copytestnew {
public void copy(String old, String newone, int x, int y) {
// Location of file to read
File file = new File(old);
Scanner scanner = new Scanner(file);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file2 = new File(newone);
output = new BufferedWriter(new FileWriter(file2, true));
output.write(line);
output.write(newLine);
output.close();
i++;
}
scanner.close();
System.out.println("File copied");
}
}
I remember you! I answeared you last time on how to replace the char at one of the lines.
First, change the decleration to
public static void copy(String old, String newone, int x, int y) throws IOException {
NOTICE the throws statment!
And now when you want to call this method you should use it inside a try-catch block or declear that you throwing exception same as you did at the copy function.
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
You're defining a function inside a method. As all functions in java are methods (static or non-static), this is not permitted. Try this:
class IDontKnowHowToNameIt {
public static void copy(file old, file new, int x, int y) {
//...
// call readFile from here
// ...
}
private static void readFile() throws Exception {
//...
}
}
I have two files. One file counts the number of listed events I have in a text file and stores the number of events into the variable "count". I want to then use the value in this variable to do computation in a second file. How do I do this? Do I have to create an object of the class in my first file and then reference it? I need an example please, I cannot seem to get this to work. Here is what I have tried.
My first file:
import java.util.*;
import java.io.*;
public class EventCounter {
public static void main (String [] args) throws IOException{
Scanner file = new Scanner(new File("event.txt"));
int count = 0;
while (file.hasNextLine()) {
count++;
file.nextLine();
}
System.out.println(count); //test
}
}
My Second file:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadEventFile {
private String path;
public ReadEventFile(String file) {
path = file;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
EventCounter method = new EventCounter(); //make object?
String[] dataTable = new String[count];
int i;
for (i=0; i<count; i++) { //Why count does not exist?
}
My second file does not know that count is a variable from my first file :-(
You seem to have your process flow backwards. The class with the main method will be created and run by the JVM - therefore it's your entry point.
Your ReadEventFile class therefore needs to be told the count when it is created. Simply add it to the constructor:
public static class ReadEventFile {
private final File eventFile;
private final int count;
public ReadEventFile(final int count, final File eventFile) {
this.eventFile = eventFile;
this.count = count;
}
public String[] openFile() throws IOException {
String[] dataTable = new String[count];
int i;
for (i = 0; i < count; i++) {
}
return dataTable;
}
}
Now your EventCounter needs to create a ReadEventFile instance once it knows the count and call the openFile method on it:
public static void main(String[] args) throws IOException {
final File eventFile = new File("event.txt");
int count = 0;
try (Scanner file = new Scanner(eventFile)) {
while (file.hasNextLine()) {
count++;
file.nextLine();
}
}
final ReadEventFile readEventFile = new ReadEventFile(count, eventFile);
final String[] dataTable = readEventFile.openFile();
}
The ReadEventFile does it's work and then returns the String[] back to your EventCounter.
You don't close any of your resources when you are done with them. This is asking for trouble. I have added a Java 7 try-with-resources around your Scanner in the EventCounter.
The design of this program does seem a little odd. There is no logical reason why the EventCounter should be the entry point to the application. I would recommend you create a BootStrap class that holds the main method and is the entry point that then calls both the EventCounter and the ReadEventFile.
Further, the openFile method on the ReadEventFile class isn't well named - it does more than that. Maybe processEventFile or something along those lines would be more appropriate.
your first Program
package farzi;
import java.util.*;
import java.io.*;
public class EventCounter {
public static void main (String [] args) throws IOException
{
EventCounter object = new EventCounter();
System.out.println(object.returnCount());
}
public int returnCount() throws FileNotFoundException
{
Scanner file = new Scanner(new File("event.txt"));
int count = 0;
while (file.hasNextLine()) {
count++;
file.nextLine();
}
System.out.println(count); //test
return count;
}
}
your second program
package farzi;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadEventFile
{
private String path;
public ReadEventFile(String file)
{
String path = file;
}
public String[] OpenFile() throws IOException {
EventCounter eventCounterObject = new EventCounter();
int countLocal = eventCounterObject.returnCount();
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
EventCounter method = new EventCounter(); //make object?
String[] dataTable = new String[countLocal];
int i;
String[] textData = null;
for (i=0; i<countLocal; i++) { //Why count does not exist?
textData[i] = textReader.readLine();
}
return textData;
}
}