printing the interval from a logfile using the indices - java

Create a file called Display.java
Write a try-catch statement that attemps to create a Scanner object to read from the logfile ('logfile.txt').
If the file does not exist, catch the FileNotFoundException, print "Cannot find logfile!" then "Exiting..." and quit the program.
If the file exists, prompt the user to enter start and end indices
Print out all the lines between the start and end line numbers (inclusive).
public class CopyOfDIsplay {
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\vutom\\IdeaProjects\\COS101 TERM4 ASSIGNMENT\\src\\logfile.txt");
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
String[] Numberz = line.split(":");
Scanner s = new Scanner(System.in);
System.out.println("Enter two numbers , a start and end index separated by a space:");
String Inputs = s.nextLine();
String[] numbers = Inputs.split("\s");
String rangeMin = numbers[0];
String rangeMax = numbers[1];
int start = Integer.parseInt(rangeMin);
int end = Integer.parseInt(rangeMax);
try {
while (line != null) {
for (String num :Numberz) {
if (line.codePointAt(start) >= && line.codePointAt(end) <= end) {
System.out.println(line);
}
else {
System.out.println(line);
}
}
}
bufferedReader.close();
} catch (FileNotFoundException e) {
System.out.println("Cannot find logfile");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
System.out.println("Exiting. . . ");
}
}

Related

Array returning null

I'm trying to read into a csv file and placing the line into an array. But when I print the array out it is null.
Here is the code:
public static String[] readFile(String inFilename)
{
int lineTotal = getLineNum(inFilename);
if (lineTotal == 0)
{
System.out.println("The file is empty ");
}
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String[] resultArrayOne = new String[lineTotal + 1];
String line;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
int lineNum;
String[] resultArray = new String[lineTotal];
String info;
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
info = line;
System.out.println(info);
resultArray[lineNum] = info;
lineNum++;
}
fileStrm.close(); //Clean up the stream
resultArrayOne = resultArray;
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return resultArrayOne;
}
When printing out the line before placing it into the array the return is fine, but when placed into the array it become null.
edit:
Here is the full FileIO code:
public static String[] Import()
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the File Name: ");
String fileName = sc.nextLine();
int length = getLineNum(fileName);
String[] array = new String[length+1];
array = readFile(fileName);
return array; //array is just strings
}
public static int getLineNum(String inFilename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
lineNum++;
}
fileStrm.close(); //Clean up the stream
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return lineNum;
}
I'm not too sure how to insert a sample file but it is something like this:
SHOP1, STORE2, 45
SHOP2, SHOP1, 67
STORE6, SHOP1, 90
...
edit 2:
I added the code that uses this
String[] locationArrayOne = new String[1000];
locationArrayOne = FileIO.Import();
for (int yyy = 0; yyy < locationArrayOne.length; yyy++)
{
System.out.print(locationArray[yyy]);
}
Your code looks fine but here is how I would debug the problem:
Before lineNum++, I will print the value of resultArray[lineNum] instead of info to see if the program was able to retrieve the line and store it to the array.
Remove the initialization of String[] resultArrayOne and after fileStrm.close(), use resultArrayOne = resultArray.clone() to copy the values of resultArray to resultArrayOne. Copying an array by assignment (array1 = array2) could have side-effects you do not want in your program since you are making both arrays refer to the same object. Check this related question here
Also, why not use resultArrayOne directly when storing the lines?

When importing a txt file, is there a way to specify how you want it formatted? [duplicate]

How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.

Searching string from text file

I'm trying to search a certain string from an input file. Firstly, the code stores data from input file and then it searches the user input data in the text file, but when i try to print one of the variables it ends up being null.
public class Test {
public static void main(String args[])throws IOException, FileNotFoundException {
BufferedReader input = null;
PrintWriter output = null;
try {
input = new BufferedReader (new FileReader ("kolej.txt"));
Scanner in = new Scanner(System.in);
in.useDelimiter("\n");
int index = 0;
String indata = null;
System.out.println("UITM College and Non-Residents Registration System");
System.out.println("Enter your student id: ");
String matrix = in.next();
UITM student[] = new UITM[10];
//storing data into array
while ((indata = input.readLine())!= null) {
StringTokenizer st = new StringTokenizer(indata,";");
student[index] = new Kolej(st.nextToken(), st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), st.nextToken(),Integer.parseInt(st.nextToken()), st.nextToken(),Integer.parseInt(st.nextToken())) ;
index++;
}
//searching
Scanner txtscan = new Scanner(new File("kolej.txt"));
while(txtscan.hasNextLine()) {
matrix = txtscan.nextLine();
if(matrix.indexOf("word") != -1) {
System.out.println(student[0].getName());
}
}
input.close();
output.close();
}
catch (FileNotFoundException fnfe) {
System.out.println("File not found");
}
catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

Reading every char in a text file

I'm attempting to read in every character (tabs, new lines) in a text file. I'm having some trouble reading all of these in. My current method reads the tabs in but not new lines. Here is the code:
//reads each character in as an integer value returns an arraylist with each value
public static ArrayList<Integer> readFile(String file) {
FileReader fr = null;
ArrayList<Integer> chars = new ArrayList<Integer>(); //to be returned containing all commands in the file
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int tempChar = ' ';
String tempLine = "";
while ((tempLine = br.readLine()) != null) {
for (int i = 0; i < tempLine.length(); i++) {
int tempIntValue = tempLine.charAt(i);
chars.add(tempIntValue);
}
}
fr.close();
br.close();
} catch (FileNotFoundException e) {
System.out.println("Missing file");
System.exit(0);
} catch (IOException e) {
System.out.println("Empty file");
System.exit(0);
}
return chars;
}
I originally used the read() method instead of readLine() but that had the same problem. I'm representing the char as ints. Any help is really appreciated!
I suggest you use try-with-resources, List and the diamond operator <> and that you read each char with the BufferedReader.read() method.
public static List<Integer> readFile(String file) {
List<Integer> chars = new ArrayList<>();
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);) {
int ch;
while ((ch = br.read()) != -1) {
chars.add(ch);
}
} catch (FileNotFoundException e) {
System.out.println("Missing file");
System.exit(0);
} catch (IOException e) {
System.out.println("Empty file");
System.exit(0);
}
return chars;
}
The reason you aren't getting line endings is documented by the BufferedReader.readLine() Javadoc which says in part (emphasis added),
A String containing the contents of the line, not including any line-termination characters...

How to read in information from a file, and store it as a string. Java

ive gotten this far, but this doesnt work to read in the file, thats the part im stuck on. i know that you need to use the scanner, but im not sure what im missing here. i think it needs a path to the file also, but i dont know where to put that in
public class string
{
public static String getInput(Scanner in) throws IOException
{
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter file");
String filename =keyboard.next();
File inputFile = new File(filename);
Scanner input = new Scanner(inputFile);
String line;
while (input.hasNext())
{
line= input.nextLine();
System.out.println(line);
}
input.close();
}
if(filename.isEmpty())
{
System.out.println("Sorry, there has been an error. You must enter a string! (A string is some characters put together.) Try Again Below.");
return getInput(in);
}
else
{
return filename;
}
}
public static int getWordCount(String input)
{
String[] result = input.split(" ");
return result.length;
}
public static void main(String[] args)
{
DecimalFormat formatter = new DecimalFormat("0.##");
String input = getInput(new Scanner(System.in));
float counter = getWordCount(input);
System.out.println("The number of words in this string ("+input+") are: " + counter);
Scanner keyboard= new Scanner(System.in);
}
}
//end of code
First of all, when doing file I/O in Java, you should properly handle all exceptions and errors that can occur.
In general, you need to open streams and resources in a try block, catch all exceptions that happen in a catch block and then close all resources in a finally block. You should read up more on these here as well.
For using a Scanner object, this would look something like:
String token = null;
File file = null;
Scanner in = null;
try {
file = new File("/path/to/file.txt");
in = new Scanner(file);
while(in.hasNext()) {
token = in.next();
// ...
}
} catch (FileNotFoundException e) {
// if File with that pathname doesn't exist
e.printStackTrace();
} finally {
if(in != null) { // pay attention to NullPointerException possibility here
in.close();
}
}
You can also use a BufferedReader to read a file line by line.
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// ...
}
With added exception handling:
String line = null;
FileReader fReader = null;
BufferedReader bReader = null;
try {
fReader = new FileReader("/path/to/file.txt");
bReader = new BufferedReader(fReader);
while ((line = bReader.readLine()) != null) {
// ...
}
} catch (FileNotFoundException e) {
// Missing file for the FileReader
e.printStackTrace();
} catch (IOException e) {
// I/O Exception for the BufferedReader
e.printStackTrace();
} finally {
if(fReader != null) { // pay attention to NullPointerException possibility here
try {
fReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bReader != null) { // pay attention to NullPointerException possibility here
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In general, use the Scanner for parsing a file, and use the BufferedReader for reading the file line by line.
There are other more advanced ways to perform reading/writing operations in Java. Check out some of them here

Categories

Resources