You have to iterate the files array and call getName() for each file:
String[] names = new String[files.length];
for (int i = 0; i < files.length; i++) {
names[i] = files[i].getName();
}
Answer from AlexR on Stack OverflowYou have to iterate the files array and call getName() for each file:
String[] names = new String[files.length];
for (int i = 0; i < files.length; i++) {
names[i] = files[i].getName();
}
Java 1.8, if you want get as List, just remove cast and to array
String[] files = (String[])Arrays.asList(dir.listFiles(filefilter))
.stream().map(x->x.getName())
.collect(Collectors.toList())
.toArray();
You don't need to convert the whole array. Just call File's getAbsolutePath() method:
driver.findElement(By.id(id1)).sendKeys(listOfFiles[1].getAbsolutePath());
But if you do want to convert the whole array, here is the Java 8 way to do this (simplified by @RemigiusStalder):
String listOfPaths[] = Arrays.stream(listOfFiles).map(File::getAbsolutePath)
.toArray(String[]::new);
Just call File.list() instead.
Assuming that it's the file paths you want, just create a String array of the same size, and iterate through the arrays getting the file paths and putting them in the String array:
String[] myStrings = new String[myFiles.length()];
for( int i = 0; i < myFiles.length(); i++ )
{
myStrings[i] = myFiles[i].getPath();
}
Same for file names or whatever, just call the method for the string you want. I haven't written Java for a while, so the syntax might be slightly off, but that should give you the idea.
Assuming you want the file names, just use
String[] myFileNames = myDirectory.list();
It does the same thing as listFiles but instead of returning File objects it returns Strings[] of the file/directory names.
First, this is not a good application of the enhanced for-loop which masks the iterator variable. Second, I'm not sure which FTPFile implementation you're using, but I'll offer this snippet, assuming your use of Apache Commons FTPFile.
String[] strings = new String[files.length];
for(int i = 0; i < files.length; i++){
strings[i] = files[i].getName(); // or whatever method call your FTPFile has
}
Just declare an Array of String that will hold your file names, and change the for loop based on an index so you can assign each element of the fileNames array a value
FTPFile[] files = client.list();
String[] fileNames = new String[files.length];
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
//Just add the file name to the array of Strings
fileNames[i] = files[i].getName();
}
Here is some example code to help you get started:
package com.acme;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileArrayProvider {
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
And an example unit test:
package com.acme;
import java.io.IOException;
import org.junit.Test;
public class FileArrayProviderTest {
@Test
public void testFileArrayProvider() throws IOException {
FileArrayProvider fap = new FileArrayProvider();
String[] lines = fap
.readLines("src/main/java/com/acme/FileArrayProvider.java");
for (String line : lines) {
System.out.println(line);
}
}
}
Hope this helps.
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
// ...
Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});
If you use Java 7 it can be done in two lines thanks to the Files#readAllLines method:
List<String> lines = Files.readAllLines(yourFile, charset);
String[] arr = lines.toArray(new String[lines.size()]);
Use a BufferedReader to read the file, read each line using readLine as strings, and put them in an ArrayList on which you call toArray at end of loop.
Stored as strings:
public class ReadTemps {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
String token1 = "";
// for-each loop for calculating heat index of May - October
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");
// Original answer used LinkedList, but probably preferable to use ArrayList in most cases
// List<String> temps = new LinkedList<String>();
List<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
for (String s : tempsArray) {
System.out.println(s);
}
}
}
For floats:
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class ReadTemps {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
// for-each loop for calculating heat index of May - October
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");
// Original answer used LinkedList, but probably preferable to use ArrayList in most cases
// List<Float> temps = new LinkedList<Float>();
List<Float> temps = new ArrayList<Float>();
// while loop
while (inFile1.hasNext()) {
// find next line
float token1 = inFile1.nextFloat();
temps.add(token1);
}
inFile1.close();
Float[] tempsArray = temps.toArray(new Float[0]);
for (Float s : tempsArray) {
System.out.println(s);
}
}
}
If you don't know the number of lines in your file, you don't have a size with which to init an array. In this case, it makes more sense to use a List :
List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
tokens.add(inFile1.nextLine());
}
After that, if you need to, you can copy to an array :
String[] tokenArray = tokens.toArray(new String[0]);
You can't cast a File to String, cause a File is not a String.
However File has a few methods (getName(), getAbsolutePath()) that return a String.
So you can do :
String[] stringArray = new String[objectArray.length];
for (int i = 0; i < objectArray.length; i++) stringArray[i] = objectArray[i].getAbsolutePath();
you could do this
File[] files =getXMLFiles(new File("C:\\some-path"));
fileArray = new String[files.length];
for (int i = 0; i < files.length; ++i){
fileArray[i] = files[i].getName();
}
Use a java.util.Scanner and java.util.List.
Scanner sc = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
FileUtils.readLines(new File("/path/filename"));
From apache commons-io
This will get you a List of String. You can use List.toArray() to convert, but I'd suggest staying with List.
Another alternative to System.arraycopy:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
In Java 8:
String[] strings = Arrays.stream(objects).toArray(String[]::new);
To convert an array of other types:
String[] strings = Arrays.stream(obj).map(Object::toString).
toArray(String[]::new);
The newer classes Path and Files will do.
Path path = Paths.get("C:\\Users\\emily\\Documents\\Parts.txt");
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
String[] array = lines.toArray(new String[lines.size()]);
...
} catch (IOException e) {
//Logger.getLogger(getClass().getName()).log(Level.SEVERE,
// path.toString(), e);
System.err.println("Could not read file: " + e.getMessage());
}
Best would be to use just the List.
Add the handling of a possible IOException, probably when the file could not be read.
You can try this:
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("C:\\Users\\emily\\Documents\\Parts.txt"));
String str;
ArrayList<String> temp = new ArrayList<String>();
String[] output;
while ((str = in.readLine()) != null) {
temp.add(str);
}
output = temp.toArray(new String[temp.size()]);
} catch (IOException e) {
} finally {
try { in.close(); } catch (Exception ex) { }
}