how to use relative file path to read a file in java? - java

file path is not working, input1.txt is located in the same directory as library.java.
What should i do to correct it ?
How should i give path so that it read thr text file ?
package SimpleLibrarySystem;
import java.time.LocalDateTime;
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
public class Library
{
ArrayList <Book> var = new ArrayList<Book>();
HashMap<Book, LocalDateTime> var1 = new HashMap<Book, LocalDateTime>();
public Library(String person, LocalDateTime time)
{
try{
File myfile = new File("input1.txt") ;
Scanner br = new Scanner(myfile);
String line = br.nextLine();
while ((line != null))
{
String a = line;
line = br.nextLine();
String b = line;
Book a1 = new Book(a,b,person);
Book a2 = new Book (a,b, "");
var.add(a2);
var1.put(a1,time);
//System.out.println(a + " "+ b);
line = br.nextLine();
}
br.close();
}
catch (Exception e)
{
System.out.println("not working");
}
}
}

with code:
public class Main{
public static void main(String[] args) {
int counter = 0;
try (FileReader fileReader = new FileReader("src/file.txt"); Scanner sc = new Scanner(fileReader)) {
while (sc.hasNextLine()) {
++counter;
sc.nextLine();
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage());
}
System.out.println(counter);
}
}
checkout: how to read file in Java

Related

Need help searching through three files and printing out the same common lines

For now, I'm searching through the first one then sending it to the second one but the second one only prints and compares the first line.
I don't know how to make the second method start from the next line and so on. The objective is to do this with three text files but i cant even get through the first one. It has to be using bufferedreader and a while loop.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
public class scanner {
public static String line;
public static String line2;
public static String line3;
public static boolean match = false;
public static void main (String [] args) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("creditCards1.txt"));
line = in.readLine();
while (match==false && line != null)
{
System.out.println(line);
line = in.readLine();
scan2(line);
}
in.close();
}
public static boolean scan2(String line) throws IOException
{
BufferedReader in2 = new BufferedReader(new FileReader("creditCards2.txt"));
if (line2 == null || line2 == "7120-0824-9323-2825")
{
line2 = in2.readLine();
}
while(match==false && line!=null)
{
System.out.println(line2);
if(line2 == line)
{
match = true;
System.out.println("sdsds" + line);
in2.close();
break;
}
line2= in2.readLine();
break;
}
return match;
}
}
package so;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
File f1 = new File("/home/guest/Desktop/file1.txt");
File f2 = new File("/home/guest/Desktop/file2.txt");
File f3 = new File("/home/guest/Desktop/file3.txt");
try {
compareTwo(f1, f2);
compareTwo(f1, f3);
compareTwo(f2, f3);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void compareTwo(File f1, File f2) throws IOException {
String l1,l2;
try (BufferedReader r1 = new BufferedReader(new FileReader(f1))) {
while ((l1 = r1.readLine()) != null) {
try (BufferedReader r2 = new BufferedReader(new FileReader(f2))) {
while ((l2 = r2.readLine()) != null) {
if(l1.equals(l2))
System.out.println("line: " + l1 + " in file " + f1 + " exists in file " + f2);
}
}
}
}
}
}

Program never finds Scanner

I have two classes that read in a file, Project2 and CMSReader. However, in the setColumnsInFile method in the CMSReader class never finds the scanner symbol. Appreciate the help.
Here is the Project2 class.
import java.util.*;
import java.io.FileNotFoundException;
import java.io.File;
public class Project2
{
public static void main(String[] args)
{
boolean found = false;
Scanner sc = null;
String fileName = null;
try
{
fileName = args[0];
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.print("File not found! Please try again.");
System.exit(0);
}
File f = null;
try
{
f = new File(fileName);
sc = new Scanner(f);
found = true;
}
catch(FileNotFoundException e)
{
System.out.print("File not found!");
}
CMSReader inputFile = new CMSReader();
inputFile.readFile(args);
System.out.println("hello");
inputFile.setColumnsInFile(args);
System.out.println("bye");
}
}
Here is the CMSReader Class:
import java.util.*;
import java.io.*;
public class CMSReader
{
public Scanner readFile(String[] file)
{
String filename = file[0];
Scanner sc = null;
File f = null;
try
{
f = new File(filename);
sc = new Scanner(f);
}
catch(IOException e)
{
}
return sc;
}
public CMSReader()
{
}
public String setColumnsInFile(String[] file)
{
Scanner sc = null;
String numberOfVariables = null;
try
{
sc = readFile(file);
boolean flag = true;
while(sc.hasNextline() && flag == true)
{
if(sc.nextline().equals("Columns in File: "))
{
flag = false;
String splitVariables = sc.nextline();
String[] numberOfVariablesParts = splitVariables.split(": ");
numberOfVariables = numberOfVariablesParts[1];
}
}
}
catch(IOException e)
{
}
return numberOfVariables;
}
}
You have sc.Nextline in one place and sc.nextline in another.
I would recommend using an IDE like Eclipse or Intellij to help you with code completion and programming misspellings.
You have typos in your second class:
Change sc.hasNextline() to sc.hasNextLine() and sc.nextline() to sc.nextLine()
Also remove the try & catch of IOException since it will never be thrown.

Java I/O writing, mixingcase and getExtension problems

I am changing names of all files in directory and if it's text file I am changing the content but it doesn't seem to work the name of the file is changed right but content is blank/gone heres is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
public class FileOps {
public static File folder = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files");
public static File[] listOfFiles = folder.listFiles();
public static void main(String[] argv) throws IOException {
toUpperCase();
}
public static void toUpperCase() throws FileNotFoundException {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String newname = mixCase(listOfFiles[i].getName());
if (listOfFiles[i].renameTo(new File(folder, newname))) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(listOfFiles[i]);
System.out.println("Done");
}
}
} else {
System.out.println("Nope");
}
}
}
public static String mixCase(String in) {
StringBuilder sb = new StringBuilder();
if (in != null) {
char[] arr = in.toCharArray();
if (arr.length > 0) {
char f = arr[0];
boolean first = Character.isUpperCase(f);
for (int i = 0; i < arr.length; i++) {
sb.append((first) ? Character.toLowerCase(arr[i])
: Character.toUpperCase(arr[i]));
first = !first;
}
}
}
return sb.toString();
}
public static void rewrite(File file) throws FileNotFoundException {
FileReader reader = new FileReader(file.getAbsolutePath());
BufferedReader inFile = new BufferedReader(reader);
try {
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
inFile.close();
outw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There is several issue with your code:
Your rewrite function is perform on old name File. It should be done on the renamed File:
String newname = mixCase(listOfFiles[i].getName());
File renamedFile = new File(folder, newname);
if (listOfFiles[i].renameTo(renamedFile )) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(renamedFile);
System.out.println("Done");
}
}
you are trying to read docx and pdf file like regular text file. This cannot work. You will have to use external library like POI and pdf Box
Your rewrite function is not safe. You must unsure to close the ressources:
FileReader reader = null;
BufferedReader inFile = null;
try {
reader = new FileReader(file.getAbsolutePath());
inFile = new BufferedReader(reader);
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally
{
if(infile != null)
inFile.close();
if(reader != null)
reader .close();
}
You can't re-write a file on top of itself. you need to write the new content to a new file, then rename again.

ReadFile cannot be resolved to a type

I am consider a rookie and I have searched for hours on the internet to solve my problem but still no luck.
I really want to understand java and if you could explain some detail that will be highly grateful.
The problem is in this line
ReadFile file = ReadFile(file_name);
error message : "ReadFile cannot be resolved to a type."
Here is my code: FileData.java
package textfiles;
import java.io.IOException;
public class FileData {
public static void main (String[] args) throws IOException {
String file_name = "D:/java/readfile/test.txt";
try {
ReadFile file = ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i =0; i < aryLines.length ; i++) {
System.out.println( aryLines[i] );
}
}
catch (IOException e) {
System.out.println( e.getMessage() );
}
}
}
And this is my other code: ReadFile.java
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private String path;
public ReadFile (String file_path) {
path = file_path;
}
int readLines () throws IOException{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine() ) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile () throws IOException {
FileReader fr = new FileReader (path);
BufferedReader textReader = new BufferedReader (fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[i] =textReader.readLine();
}
textReader.close();
return textData;
}
}
Try this:
ReadFile file = new ReadFile(file_name);
In order to initialize an object with it's class name you should use the new key word like this:
ClassName objName = new ClassName(arguments);
From the rest of your code seems you know the notion, nevertheless I refer you (or possible future visitors) to this page.

Run two classes one after the other

How to run two classes in which one gives some data in a textfile & the other should take that file and process it?
I have two Java files. File1 processes something and outputs a text file. File2 should take that text file and process it to create a final output.
My requirement is to have two independent java files that work together.
File1
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class FlatFileParser
{
public static void main(String[] args)
{
try
{
// The stream we're reading from
BufferedReader in;
List<String> ls = new ArrayList<String>();
BufferedWriter out1 = new BufferedWriter(new FileWriter("inValues.txt" , true ));
BufferedReader out11 = new BufferedReader(new FileReader("inValues.txt"));
// Return value of next call to next()
String nextline;
String line="";
if (args[0].equals("1"))
{
in = new BufferedReader(new FileReader(args[1]));
nextline = in.readLine();
while(nextline != null)
{
nextline = nextline.replaceAll("\\<packet","\n<packet");
System.out.println(nextline);
nextline = in.readLine();
}
in.close();
}
else
{
in = new BufferedReader(new FileReader(args[1]));
nextline = in.readLine();
HashMap<String,String> inout = new HashMap<String,String>();
while(nextline != null)
{
try
{
if (nextline.indexOf("timetracker")>0)
{
String from = "";
String indate = "";
if (nextline.indexOf("of in")>0)
{
int posfrom = nextline.indexOf("from");
int posnextAt = nextline.indexOf("#", posfrom);
int posts = nextline.indexOf("timestamp");
from = nextline.substring(posfrom+5,posnextAt);
indate = nextline.substring(posts+11, posts+23);
String dd = indate.split(" ")[1];
String key = dd+"-"+from+"-"+indate;
//String key = from+"-"+indate;
String intime = "-in-"+nextline.substring(posts+24, posts+35);
inout.put(key, intime);
}
else if (nextline.indexOf("of out")>0)
{
int posfrom = nextline.indexOf("from");
int posnextAt = nextline.indexOf("#", posfrom);
int posts = nextline.indexOf("timestamp");
from = nextline.substring(posfrom+5,posnextAt);
indate = nextline.substring(posts+11, posts+23);
String dd = indate.split(" ")[1];
String key = dd+"-"+from+"-"+indate;
String outtime = "-out-"+nextline.substring(posts+24, posts+35);
if (inout.containsKey(key))
{
String val = inout.get(key);
if (!(val.indexOf("out")>0))
inout.put(key, val+outtime);
}
else
{
inout.put(key, outtime);
}
}
}
}
catch(Exception e)
{
System.err.println(nextline);
System.err.println(e.getMessage());
}
nextline = in.readLine();
}
in.close();
for(String key: inout.keySet())
{
String val = inout.get(key);
out1.write(key+" , "+val+"\n");
}
out1.close();
}
}
catch (IOException e)
{
throw new IllegalArgumentException(e);
}
}
File2
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.FileReader;
public class RecordParser
{
private static BufferedReader reader;
private List<Person> resource;
private List<String> finalRecords;
public RecordParser(BufferedReader reader)
{
this.reader = reader;
this.resource = new ArrayList<Person>();
this.finalRecords = new ArrayList<String>();
}
public void execute() throws IOException
{
String line = null;
while ((line = reader.readLine()) != null)
{
String[] parts = line.split(" , ");
addPerson(new Person(parts[0]));
if ((parts[1].contains("-in-")) && (parts[1].contains("-out-")))
{
String[] inout = parts[1].split("-out-");
Person person = getPerson(parts[0]);
person.setInTime(inout[0]);
person.setOutTime("-out-" + inout[1]);
}
else if (parts[1].contains("-in-"))
{
Person person = getPerson(parts[0]);
person.setInTime(parts[1]);
}
else
{
Person person = getPerson(parts[0]);
person.setOutTime(parts[1]);
}
}
// finalRecords the resource to the String list
for (Person p : resource)
{
finalRecords.add(p.getPerson());
}
}
private void addPerson(Person person)
{
for (Person p : resource)
{
if (p.getNameDate().equals(person.getNameDate()))
{
return;
}
}
resource.add(person);
}
private Person getPerson(String nameDate)
{
for (Person p : resource)
{
if (p.getNameDate().equals(nameDate))
{
return p;
}
}
return null;
}
public List<String> getfinalRecords()
{
return finalRecords;
}
public static void main(String[] args)
{
try {
BufferedReader reader = new BufferedReader(new FileReader("sample.txt"));
RecordParser recordParser = new RecordParser(reader);
recordParser.execute();
for (String s : recordParser.getfinalRecords())
{
System.out.println(s);
}
reader.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
public class Person
{
private String nameDate;
private String inTime;
private String outTime;
public Person (String nameDate)
{
this.nameDate = nameDate;
this.inTime = "missing in";
this.outTime = "missing out";
}
public void setInTime(String inTime)
{
this.inTime = inTime;
}
public void setOutTime(String outTime)
{
this.outTime = outTime;
}
public String getNameDate()
{
return nameDate;
}
public String getPerson()
{
StringBuilder builder = new StringBuilder();
builder.append(nameDate);
builder.append(" , ");
builder.append(inTime);
builder.append(" , ");
builder.append(outTime);
return builder.toString();
}
}
}
I want to be able to import the values from inValues.txt (created in File1) and process them in File2.
Create a batch/sh file and run one java program after the other. If you want to pass the file details to the second program you can do that by providing a run time argument.
on windows:
java -classpath .;yourjars FlatFileParser
java -classpath .;yourjars RecordParser {optionalfiledetails}
on linux
java -classpath .:yourjars FlatFileParser
java -classpath .:yourjars RecordParser {optionalfiledetails}

Categories