Why cant the system find the file that is specified? - java

in the assignment, the code is suppose to print on a single word from each file that repeats the most. I used a path to get to the list of files used for this assignment and i put them into an array. i cannot seems to find the problem as the array has all the files in it set to string. So why cant it find my file?
below is my code for single thread:
import java.io.*;
import java.util.*;
public class SingleThreaded {
public static void main(String[] args) throws IOException {
File directoryPath = new File("C:\\assignment 3\\links");
String[] dir = directoryPath.list();
System.out.println(Arrays.toString(dir));
String result;
//Scanner scan;
//try{
//Scanner scan = new Scanner(System.in);
long startTime = System.nanoTime();
for (String file : dir) {
//if(file.isFile()){
//BufferedReader inputStream = null;
String line;
//int i;
try{
//inputStream = new BufferedReader(new FileReader(file));file
Scanner scan = new Scanner(new File(file));
HashMap<String, Integer> map = new HashMap<>();
while (scan.hasNextLine()){
line = scan.nextLine().replaceAll("\\p{Punct}", " ");
String[] word = line.split("\s+");
for (int i = 0; i < word.length; i++) {
String string = word[i].toLowerCase();
if (string.length() >= 5) {
if (map.containsKey(string)) {
map.put(string, map.get(string) + 1);
} else {
map.put(string, 1);
}
}
}
}
result = Collections.max(map.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
System.out.println( file + ": " + result);
}catch (FileNotFoundException e) {
e.printStackTrace();
}
/* }finally{
if(inputStream != null){
inputStream.close();
}
}
*/
// }
}
long endTime = System.nanoTime();
long totalTime = (endTime - startTime)/1000;
System.out.print("Total Time: " + totalTime);
//} catch (FileNotFoundException e) {
//e.printStackTrace();
//}
}
}
I tried changing the path and using different built-in methods but nothing seems to work.

Try this:
public static void main(String[] args) throws IOException {
File directoryPath = new File("C:\\assignment 3\\links");
File[] files = directoryPath.listFiles();
for (File file : files) {
Scanner scan = new Scanner(file);
Notice the difference, using File.listFiles() instead of File.list().

Related

How to sort a cvs file by one field in Java?

How can I sort a cvs file by one field in Java?
For example I want to sort it by the third field
I have a cvs file that looks like this:
1951,Jones,5
1984,Smith,7
...
I tried using Scanner as such, with a delimiter but I couldn't figure out how to go on:
public static void main(String[] args)
{
//String data = args[0];
Scanner s = null;
String delim = ";";
try
{
s = new Scanner(new BufferedReader (new FileReader("test.csv")));
List<Integer> three = new ArrayList<Integer>();
while(s.hasNext())
{
System.out.println(s.next());
s.useDelimiter(delim);
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
finally
{
if(s != null)
{
s.close();
}
}
}
Thank you!
public static void main(String[] args)
{
final String DELIM = ";";
final int COLUMN_TO_SORT = 2; //First column = 0; Third column = 2.
List<List<String>> records = new ArrayList<>();
try (Scanner scanner = new Scanner(new File("test.csv"))) {
while (scanner.hasNextLine()) {
records.add(getRecordFromLine(scanner.nextLine(), DELIM));
}
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
Collections.sort(records, new Comparator<List<String>>(){
#Override
public int compare(List<String> row1, List<String> row2){
if(row1.size() > COLUMN_TO_SORT && row2.size() > COLUMN_TO_SORT)
return row1.get(COLUMN_TO_SORT).compareTo(row2.get(COLUMN_TO_SORT));
return 0;
}
});
for (Iterator<List<String>> iterator = records.iterator(); iterator.hasNext(); ) {
System.out.println(iterator.next());
}
}
private static List<String> getRecordFromLine(String row, String delimiter) {
List<String> values = new ArrayList<String>();
try (Scanner rowScanner = new Scanner(row)) {
rowScanner.useDelimiter(delimiter);
while (rowScanner.hasNext()) {
values.add(rowScanner.next());
}
}
return values;
}
** Note that the example file is separated by comma, but in the code you use semicolon as the delimiter.

Why my Java program works perfectly in windows but it's a disaster in linux?

I wrote a program that reads a text file, deletes the requested string and rewrites it without the string. This program takes three arguments from the terminal: 1) the input file 2) the string 3) the output file.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class wordfilter {
public static void main(String[] args) {
Scanner scanner = new Scanner("");
Scanner conteggio = new Scanner("");
int numel = 0;
File file = new File(args[0]); // Argomento 0: il file
try {
conteggio = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (conteggio.hasNext()) {
numel++;
conteggio.next();
}
conteggio.close();
String[] lettura = new String[numel];
int i = 0;
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
System.out.println("Contarighe -> " + numel);
for (i = 0; i < lettura.length; i++) {
System.out.println("Elemento " + i + " - > " + lettura[i]);
}
scanner.close();
String escludi = args[1]; // Argomento 1: il filtro
String[] filtrato = rimuovi(escludi, lettura);
if (args.length == 3) stampaSuFile(filtrato, args[2]);
}
public static String[] rimuovi(String esclusione, String[] input) {
String[] nuovoV;
String escludi = esclusione;
int dim = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi))
dim++;
}
nuovoV = new String[dim];
int j = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi)) {
nuovoV[j] = input[i];
j++;
}
;
}
return nuovoV;
}
public static void stampaSuFile(String[] out, String path) {
String closingstring = "";
File destinazione = new File(path);
try {
destinazione.createNewFile();
} catch (IOException e) {
System.out.println("Errore creazione file");
}
try {
FileWriter writer = new FileWriter(destinazione);
for (int i = 0; i < out.length; i++)
writer.write(out[i] + (i == (out.length-1) ? closingstring : " "));
writer.close();
System.out.println("Scrittura eseguita correttamente");
} catch (IOException e) {
System.out.println("Errore scrittura file");
}
}
}
On Windows no problem, it works perfectly.
On Linux instead when i write something like java wordfilter in.txt word out.txt
I get
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at wordfilter.main(wordfilter.java:42)
What's the problem? It's because of some difference on linux?
You're mixing line and token based functions, :hasNextLine() and next(). If the input ends with a line feed (typical on Linux) hasNextLine returns true at the end of the file, but there is no next "item".
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
You should use either hasNext with next, or hasNextLine with nextLine, mixing them is confusing.
while (scanner.hasNext()) {
lettura[i] = scanner.next();
i++;
}
The input file ends in a newline on Linux. Therefore, there's another line, but it's empty. If you remove the final newline from the input, the program will start working normally.
Or, import the exception
import java.util.NoSuchElementException;
and ignore it int the code
while (scanner.hasNextLine()) {
System.out.println("" + i);
try {
lettura[i] = scanner.next();
} catch (NoSuchElementException e) {}
i++;
}

Reading text file always returns 0 - Java

I'm trying to read a text file to get a version number but for some reason no matter what I put in the text file it always returns 0 (zero).
The text file is called version.txt and it contains no spaces or letters, just 1 character that is a number. I need it to return that number. Any ideas on why this doesn't work?
static int i;
public static void main(String[] args) {
String strFilePath = "/version.txt";
try
{
FileInputStream fin = new FileInputStream(strFilePath);
DataInputStream din = new DataInputStream(fin);
i = din.readInt();
System.out.println("int : " + i);
din.close();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
private final int VERSION = i;
Here is the default solution that i use whenever i require to read a text file.
public static ArrayList<String> readData(String fileName) throws Exception
{
ArrayList<String> data = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String temp = in.readLine();
while (temp != null)
{
data.add(temp);
temp = in.readLine();
}
in.close();
return data;
}
Pass the file name to readData method. You can then use for loop to read the only line in the arraylist, and can use the same loop to read multiple lines from different file...I mean do whatever you like with the arraylist.
Please don't use a DataInputStream
Per the linked Javadoc, it lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
You want to read a File (not data from a data output stream).
Please do use try-with-resources
And since you seem to want an ascii integer, I'd suggest you use a Scanner.
public static void main(String[] args) {
String strFilePath = "/version.txt";
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
int i = scanner.nextInt();
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
}
Use an initializing block
An initializing block will be copied into the class constructor, in your example remove public static void main(String[] args), something like
private int VERSION = -1; // <-- no more zero!
{
String strFilePath = "/version.txt";
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
VERSION = scanner.nextInt(); // <-- hope it's a value
System.out.println("Version = " + VERSION);
} catch (Exception e) {
e.printStackTrace();
}
}
Extract it to a method
private final int VERSION = getVersion("/version.txt");
private static final int getVersion(String strFilePath) {
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
VERSION = scanner.nextInt(); // <-- hope it's a value
System.out.println("Version = " + VERSION);
return VERSION;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
or even
private final int VERSION = getVersion("/version.txt");
private static final int getVersion(String strFilePath) {
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
if (scanner.hasNextInt()) {
return scanner.nextInt();
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}

How do i load a text file into this program?

How do i go about loading a text file into a java program that i have posted below. I have tried but am out of luck, any help will be appreciated!
Thank you.
import java.io.*;
public class test1 {
public static void main(String args[]) throws Exception {
if (args.length != 1) {
System.out.println("usage: Tut16_ReadText filename");
System.exit(0);
}
try {
FileReader infile = new FileReader(args[0]);
BufferedReader inbuf = new BufferedReader(infile);
String str;
int totalwords = 0, totalchar = 0;
while ((str = inbuf.readLine()) != null) {
String words[] = str.split(" ");
totalwords += words.length;
for (int j = 0; j < words.length; j++) {
totalchar += words[j].length();
}
}
double density = (1.0 * totalchar) / totalwords;
if (totalchar > 0) {
System.out.print(args[0] + " : " + density + " : ");
if (density > 6.0)
System.out.println("heavy");
else
System.out.println("light");
} else
System.out.println("This is an error - denisty of zero.");
infile.close();
} catch (Exception ee) {
System.out.println("This is an error - execution caught.");
}
}
}
If you are running java 8 it is a breeze with the new io streams. Advantage is on large file all text is not read into memory.
public void ReadFile(String filePath){
File txtFile = new File(filePath);
if (txtFile.exists()) {
System.out.println("reading file");
try (Stream<String> filtered = Files.
lines(txtFile.toPath()).
filter(s -> s.contains("2006]"))) {//you can leave this out, but is handy to do some pre filtering
filtered.forEach(s -> handleLine(s));
}
} else {
System.out.println("file not found");
}
}
private void handleLine(String lineText) {
System.out.println(lineText);
}
First of all, there is an easier way to read files. From Java 7 the Files and Paths classes can be used like this:
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("usage: Tut16_ReadText filename");
System.exit(0);
}
final List<String> lines = Files.readAllLines(Paths.get(args[0]));
for (String line : lines) {
// Do stuff...
}
// More stuff
}
Then, in order to start the program and get it to read a file that you specify you must provide an argument when starting the app. You pass that argument after the class name on the command prompt like this:
$ java Tut16_ReadText /some/path/someFile.txt
This passes "/some/path/someFile.txt" to the program and then the program will try to read that file.
Another method is to use a Scanner.
Scanner s = new Scanner(new File(args[0]));
while(s.hasNext()){..}

Merge Two text files line by line using java

First text file
A.txt;
asdfghjklqw12345 qwe3456789
asdfghjklqw12345 qwe3456789
Second text file
B.txt;
|Record 1: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
|Record 2: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
Third text file
C.txt;
asdfghjklqw12345 qwe3456789 |Record 1: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
asdfghjklqw12345 qwe3456789 |Record 2: Rejected - Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
for the above situation where I want to merge two lines from two different text files into one line.My code is below
List<FileInputStream> inputs = new ArrayList<FileInputStream>();
File file1 = new File("C:/Users/dell/Desktop/Test/input1.txt");
File file2 = new File("C:/Users/dell/Desktop/Test/Test.txt");
FileInputStream fis1;
FileInputStream fis2;
try {
fis1 = new FileInputStream(file1);
fis2= new FileInputStream(file2);
inputs.add(fis1);
inputs.add(fis2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int total = (int) (file1.length() + file2.length());
System.out.println("total length is " + total);
SequenceInputStream sis = new SequenceInputStream(Collections.enumeration(inputs));
try {
System.out.println("SequenceInputStream.available() = "+ sis.available());
byte[] merge = new byte[total];
int soFar = 0;
do {
soFar += sis.read(merge,total - soFar, soFar);
} while (soFar != total);
DataOutputStream dos = new DataOutputStream(new FileOutputStream("C:/Users/dell/Desktop/Test/C.txt"));
soFar = 0;
dos.write(merge, 0, merge.length);
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here is code:
public class MergeText {
public static void main(String[] args) throws IOException{
String output="";
try(Scanner sc1=new Scanner((new File("A.txt")));
Scanner sc2=new Scanner((new File("B.txt")))){
while(sc1.hasNext() || sc2.hasNext()){
output+=sc1.next() +" "+ sc2.next();
output+="\n";
}
}
try(PrintWriter pw=new PrintWriter(new File("C.txt"))){
pw.write(output);
}
}
}
You might want to have a look at BufferedReader and BufferedWriter.
Show us what you tried and where you are stuck and we are happy to provide more help.
Merging all txt file from a folder can be done in the following way:
public static void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<String>();
//Reading data files
try {
File folder = new File("path/inputFolder");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
BufferedReader t = new BufferedReader (new FileReader (file));
String s = null;
while ((s = t.readLine()) != null) {
list.add(s);
}
t.close();
}
}
}
catch (IOException e) {
e.printStackTrace();
}
//Writing merged data file
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("data.output/merged-output.txt"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("complited");
writer.flush();
writer.close();
}
Improved on Masudul's answer to avoid compilation errors:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class MergeText {
public static void main(String[] args) throws IOException {
StringBuilder output = new StringBuilder();
try (Scanner sc1 = new Scanner((new File("C:\\Users\\YourName\\Desktop\\A.txt")));
Scanner sc2 = new Scanner((new File("C:\\Users\\YourName\\Desktop\\B.txt")))) {
while (sc1.hasNext() || sc2.hasNext()) {
String s1 = (sc1.hasNext() ? sc1.next() : "");
String s2 = (sc2.hasNext() ? sc2.next() : "");
output.append(s1).append(" ").append(s2);
output.append("\n");
}
}
try (PrintWriter pw = new PrintWriter(new File("C:\\Users\\mathe\\Desktop\\Fielddata\\RESULT.txt"))) {
pw.write(output.toString());
}
}
}

Categories

Resources