import java.io.File;
import java.util.*;
public class AppendTool {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Input Directory to Append Values: ");
String dirInput = sc.nextLine();
System.out.println("Input value to append to Directory Files: ");
String valInput = sc.nextLine();
sc.close();
File path = new File(dirInput);
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files[i]);
int where = files[i].getName().lastIndexOf(".");
String result = valInput + files[i].getName().substring(0, where) + files[i].getName().substring(where);
System.out.println(result);
File dest = new File(result);
files[i].renameTo(dest);
System.out.println(files[i]);
}
}
}
}
This tool is designed to append a value to the beginning of the filename for every filename in a directory. It seems to append the value as it should, but it deletes the files from the directory rather than rename the existing file within the same directory. Any help would be appreciated.
To rename a file in the same directory, you can use:
Files.move(source, source.resolveSibling("newName.txt"),
StandardCopyOption.REPLACE_EXISTING);
Your result variable is weird, you can just:
String result = valInput + files[i].getName();
Related
I have this code but when I run it, it can not read the file and I get this error:
Exception in thread "main" java.io.FileNotFoundException: PBM.txt (The system cannot find the file specified)
is anybody can help me which part of the code has problem?
I made a file with the name:"PBM" in my package, but it does not work!
here is my code:
import java.util.Scanner;
import java.io.*;
public class PBM {
private int[][] bits;
private int rows, columns;
PBM() throws IOException {
Scanner PBM = new Scanner(new File("PBM.txt"));
if (!PBM.next().equals("P1"))
throw new IOException("Format error");
columns = PBM.nextInt();
rows = PBM.nextInt();
bits = new int[rows][columns];
for (int i = 0; i < rows; i++) {
String line = PBM.next();
for (int j = 0; j < columns; j++)
bits[i][j] = line.charAt(j) - '0';
}
}
public String toString() {
String result = "";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (bits[i][j] == 1)
result += "*";
else
result += " ";
}
result += "\n";
}
return result;
}
public static void main(String a[]) throws IOException {
PBM Ob = new PBM();
System.out.println(Ob);
}
}
Add this (just before your read the file) to find your current working directory:
System.out.println("Working Directory = " + System.getProperty("user.dir"));
and then move PBM.txt file in the correct directory and the program should work.
NB: don't forget to remove the above line once you're done!
This exception happen because either the path to file is wrong, in your case, or the file doesn't exist.
Try to valid the path and check if the file exist. Also, as #Boris said, use the current working path to avoid a relative path as can be "PBM.txt" and to be sure what the correct path is where you application is looking for the file:
String path = System.getProperty("user.dir") + File.separator + "PBM.txt";
System.out.println("PATH: " + path);
File f = new File(path);
if(!f.exists())
{
//throw new IOException("File was not founded.");
}
Scanner PBM = new Scanner(f);
In this example the output is:
PATH: /Users/jorgeomarmedratorres/Documents/workspace/Dummy/PBM.txt
Throw File was not founded.
In my case the current working path is "/Users/jorgeomarmedratorres/Documents/workspace/Dummy"
i cannot for the life of me seem to take in the contents of this file, i keep getting No such elements exception on line 25, all help appreciate. heres a link to the file link
heres my code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class practiceFinal {
public static void main(String[] args) {
String fileName = args[0];
int length = fileLength(fileName);
int[] array = new int[length];
String[] list = new String[length];
arrayPopulate(array, list, fileName);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
}
public static int fileLength(String fileName) {
File file = new File(fileName);
Scanner fileScan = new Scanner(fileName);
int counter = 0;
while (fileScan.hasNext()) {
fileScan.next();
counter++;
}
return counter;
}
public static void arrayPopulate(int[] array, String[] list, String fileName) {
File file = new File(fileName);
Scanner fileScan = null;
try {
fileScan = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("details: " + e.getMessage());
}
for (int i = 0; i < array.length; i++) {
array[i] = fileScan.nextInt();
list[i] = fileScan.next();
}
}
}
There are a few problems here. First of all you are using fileScan.next(); to try and get the length of a file. This is going to give you 2 times the length because you are counting each token fileScan.next() grabs which will be first the number and then the letter.
Length of lines is 144 but when you calculate it, it returns 288.
So use fileScan.nextLine();, now some people have mentioned this but your program is still not going to work correctly because you passed Scanner fileScan = new Scanner(fileName); // mistake passed fileName instead of file
Here are the changes I made inside the fileLength() method:
File file = new File(fileName);
Scanner fileScan = new Scanner(file); // mistake passed fileName instead of file, changed from Scanner fileScan = new Scanner(fileName)
while (fileScan.hasNextLine()) {
fileScan.nextLine(); // changed from fileScan.next()
counter++;
}
Your output looks like:
84c89C11w71h110B96d61H92d10B3p40c97G117X13....
When you are printing the results, change the print statements to
System.out.print(array[i]);
System.out.print(" " + list[i]);
System.out.println();
Output now looks like:
84 c
89 C
11 w
71 h
....
Instead of using int length = fileLength(fileName); to find the length, use int length = fileName.length();
From the format of your file and your current code, it looks like length represents the number of "words" in the file. In your loop, you need to advance i by 2 instead of 1, since it consumes two "words" per iteration. This also means that each array is twice as long as it should be. Instantiate them with length/2.
for (int i = 0; i < array.length; i += 2) {
array[i] = fileScan.nextInt();
list[i] = fileScan.next();
}
Alternately, you could make length represent the number of lines in the file. To do that, use hasNextLine() and nextLine() in your counting loop. Then leave all of the rest of your code as-is.
while (fileScan.hasNextLine()) {
fileScan.nextLine();
counter++;
}
Additionally, make sure your Scanner is passed the proper parameters. A String is valid, but not for File I/O. You would need to first create a File object using the fileName.
Scanner fileScan = new Scanner(new File(fileName));
How to search a particular folder for a file name, that is input by the user. In my program the file is an excel spreadsheet. So if i basically use:
Scanner kbReader = new Scanner(System.in);
String fileName = kbReader.nextLine();
How would i search and open the corresponding file with the name fileName.
You need to use regular expression to match your file name like filename.matches("*"+expectedfilename+"*.xls")) on List of file names taken from directory.
String fileName = null;
File folder = new File("your/directory/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
fileName = listOfFiles[i].getName();
if(fileName.matches("*"+expectedfilename+"*.xls"))){ // put regex here
// do your code here and
// if you want to open do operation on file then file object
File file = listOfFiles[i];
}
}
}
Try this
File dir = new File("F:/");
File[] allFileName = dir.listFiles();
for (int i = 0; i < allFileName.length; i++) {
String filename = allFileName[i].getName()
if (allFileName[i].isFile()) {
if (filename.endsWith(".xls"))
System.out.println("This is a excel file with name " + filename);
}
}
I'm working on a project that takes in criteria supplied by a user, and compares it to an already created list of object containing similar criteria.
Currently, I'm trying to get the program to read the file, but I keep getting my exception and not what I want. My code for the scanner and file is as followed:
package project205;
import java.util.*;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class HouseList {
ArrayList<House> houseList = new ArrayList<House>();
public HouseList(String fileName)
{
//Open the data file
Scanner myFileIn = null;
try
{
myFileIn = new Scanner(new File("houses.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File: " + "houses.txt" + " is not found");
}
// First piece of data is the number of records
int numRecords = myFileIn.nextInt();
String address1;
int price1;
int area1;
int numBedroom1;
// Temp variable to accumulate the sum
//double sum = 0.0;
//Read the data line by line and build the
//array lists containing names and incomes
for (int k = 0; k < numRecords; k++)
{
address1 = myFileIn.next();
price1 = myFileIn.nextInt();
area1 = myFileIn.nextInt();
numBedroom1 = myFileIn.nextInt();
House house1 = new House(address1, price1, area1, numBedroom1);
houseList.add(house1);
}
// Close the input file
myFileIn.close();
}
public String getHouses(Criteria c)
{
String result = "";
for(int i = 0; i < houseList.size(); i++)
{
House h1 = houseList.get(i);
if (h1.satisfies(c))
{
result = result + h1.toString();
}
}
return result;
}
public void printHouses(Criteria c)
{
System.out.println(getHouses(c));
}
}
My file is in the same package, as I am using eclipse, but I keep getting "File: houses.txt is not found". To be thourough, the error I get is :
File: houses.txt is not found
Exception in thread "main" java.lang.NullPointerException
at project205.HouseList.<init>(HouseList.java:29)
at project205.HouseListTester.main(HouseListTester.java:7)
If anyone could even point me in the direction of what I'm missing here I would greatly appreciate it!
This may help you:
//creating File instance to reference text file in Java
File text = new File("<file location>/houses.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
//Reading each line of file using Scanner class
while(scnr.hasNextLine()){
//process file
}
Use
System.getProperty("user.dir") + System.getProperty("file.separator") + "houses.txt"
to get the file path if houses.txt and the class file from which you are trying to access shares the same directory.
you can modify
myFileIn = new Scanner(new File("houses.txt"));
//to
myFileIn = new Scanner(new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "houses.txt"));
//or
myFileIn = new Scanner(new File(System.getProperty("file.separator") + "houses.txt"));
Other case is that the file is in some other directory. In this scenario, provide relative path of this file ex.
//current dir is c: and your file is in d: then do
myFileIn = new Scanner(new File("addRelativeFilePathHere" + "houses.txt"));
Above, you need to end addRelativeFilePathHere with file.separator or prefix houses.txt with file separator.
This link to see what these properties points to and their meanings and for more inormation
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html and
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
Im probably going around this the wrong way, but My question is, how would I go about filling the array for fxRates?
CAD,EUR,GBP,USD
1.0,0.624514066,0.588714763,0.810307
1.601244959,1.0,0.942676548,1.2975
1.698615463,1.060809248,1.0,1.3764
1.234100162,0.772200772,.726532984,1.0
This is the information i have in the CSV file, I was thinking about using the scanner class to read it. Something like
private double[][] fxRates;
String delimiter = ","
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
fxRates = line.split(delimiter)
Your way of solving this problem seems OK. But line.split(",") will return a 1D String array. You cannot assign it to fxRates. And also you should know the number of lines or rows in order to initialize fxRates at the beginning. Otherwise you should use a dynamic list structure like ArrayList.
Supposing you have 50 lines in your file, you can use something like:
private String[][] fxRates = String[50][];
String delimiter = ",";
Scanner sc = new Scanner(file);
int index=0;
while (sc.hasNextLine())
{
String line = sc.nextLine();
fxRates[index++] = line.split(delimiter)
}
And note that I've declared fxRates as a 2D String array, if you need double values you should do some conversion in place or later on.
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
public class CSVReader{
private String readFile(String path, Charset encoding) throws IOException
{
//Read in all bytes from a file at the specified path into a byte array
//This method will fail if there is no file to read at the specified path
byte[] encoded = Files.readAllBytes(Paths.get(path));
//Convert the array of bytes into a string.
return new String(encoded, encoding);
}
public String readFile(String path)
{
try {
//Read the contents of the file at the specified path into one long String
String content = readFile(path, Charset.defaultCharset());
//Display the string. Feel free to comment this line out.
System.out.println("File contents:\n"+content+"\n\n");
//Return the string to caller
return content;
}catch (IOException e){
//This code will only execute if we could not open a file
//Display the error message
System.out.println("Cannot read file "+path);
System.out.println("Make sure the file exists and the path is correct");
//Exit the program
System.exit(1);
}`enter code here`
return null;
}
}
The result of a split operation is a String array, not an array of double. So one step is missing: converting the Strings to doubles:
private double[][] fxRates = new double[maxLines][4];
String delimiter = ","
int line = 0;
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] fxRatesAsString = line.split(delimiter);
for (int i = 0; i < fxRatesAsString.length; i++) {
fxRates[line][i] = Double.parseDouble(fxRatesAsString[i]);
}
Another example;
Double[][] fxRates = new Double[4][];
String delimiter = ",";
//file code goes here
Scanner sc = new Scanner(file);
// Read File Line By Line
int auxI = 0;
// Read File Line By Line
for (int auxI =0; sc.hasNextLine(); auxI++) {
String line = sc.nextLine();
System.out.println(line);
String[] fxRatesAsString = line.split(delimiter);
Double[] fxRatesAsDouble = new Double[fxRatesAsString.length];
for (int i = 0; i < fxRatesAsString.length; i++) {
fxRatesAsDouble[i] = Double.parseDouble(fxRatesAsString[i]);
}
fxRates[auxI] = fxRatesAsDouble;
}
//to double check it
for (int y =0; y<fxRates.length; y++){
for (int x =0; x<fxRates.length; x++){
System.out.print(fxRates[y][x] +" ");
}
System.out.println("");
}
I wouldn't recommend you to parse CSVs in such a way, because Scanner is too low-level and raw solution for this. In comparison, DOM/SAX parsers are better to parse XML rather than regular expressions parsing or whatever that does not consider the document structure. There are CSV parsers that feature good APIs and suggest configuration options during a reader initialization. Just take a look at easy to use CsvReader. Here is a code sample using it:
package q12967756;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import static java.lang.Double.parseDouble;
import static java.lang.System.out;
import com.csvreader.CsvReader;
public final class Main {
private Main() {
}
private static final String MOCK =
"CAD,EUR,GBP,USD\n" +
"1.0,0.624514066,0.588714763,0.810307\n" +
"1.601244959,1.0,0.942676548,1.2975\n" +
"1.698615463,1.060809248,1.0,1.3764\n" +
"1.234100162,0.772200772,.726532984,1.0\n";
private static final char SEPARATOR = ',';
public static void main(String[] args) throws IOException {
// final FileReader contentReader = new FileReader("yourfile.csv");
final StringReader contentReader = new StringReader(MOCK);
final CsvReader csv = new CsvReader(contentReader, SEPARATOR);
csv.readHeaders(); // to skip `CAD,EUR,GBP,USD`
final Collection<double[]> temp = new ArrayList<double[]>();
while ( csv.readRecord() ) {
temp.add(parseRawValues(csv.getValues()));
}
final double[][] array2d = temp.toArray(new double[temp.size()][]);
out.println(array2d[3][1]);
}
private static double[] parseRawValues(String[] rawValues) {
final int length = rawValues.length;
final double[] values = new double[length];
for ( int i = 0; i < length; i++ ) {
values[i] = parseDouble(rawValues[i]);
}
return values;
}
}