I write to program to read data file field firstname, check in data file is there any dupicate firstname if there is duplicate firstname in data file, put number at end of line like sequction number like 0,1,2....
Data file in:
CustmerNumber,FirstName,LastName,Address1,city
123456789,abcd,efgh,12 spring st,atlanta
2345678,xyz,lastname,16 sprint st,atlanta
232345678,abcd,efgh ,1201 sprint st,atlanta
1234678,xyz,lastname,1234 oakbrook pkwy,atlanta
23556,abcd,efgh,3201 sprint st,atlanta
34564,robert,parker,12032 oakbrrok,atlanta
Out File Data File like:
CustmerNumber,FirstName,LastName,Address1,city,**SEQNUMBER**
123456789,**abcd,efgh**,12 spring st,atlanta,**0**
232345678,**abcd,efgh** ,1201 sprint st,atlanta,**1**
23556,**abcd,efgh**,3201 sprint st,atlanta,**2**
2345678,**xyz,lastname**,16 sprint st,atlanta,**0**
1234678,**xyz,lastname**,1234 oakbrook pkwy,atlanta,**1**
34564,**robert,parker**,12032 oakbrrok,atlanta,**0**
My Program is working fine:
I just have one question,
Here is my program,
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class test1 {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
Map<String, Integer> names = new HashMap<>();
File dir = new File("Data_File_In");
for (File file : dir.listFiles()) {
Scanner s = new Scanner(file);
s.nextLine();
while(s.hasNextLine()) {
String line = s.nextLine();
String[] actionID = line.split("\\,");
// String PFN = actionID[0].trim();
// String PLN = actionID[1].trim();
if(!names.containsKey(actionID[0].trim())) {
names.put(actionID[0].trim(), 0);
}
names.put(actionID[0].trim(), names.get(actionID[0].trim())+1);
}
for(String name : names.keySet()) {
for(int i = 1; i <= names.get(name); i++) {
System.out.println(name + "---->" + (i-1));
}
}
s.close();
}
}
}
System.out.println(name + "---->" + (i-1));
In This line its printing Name, that's only field right?? instead of that I want to print LINE..
And in output firstline its printing:-
---->0
need to remove this line as well
Is there anyway that I can print line instead of firstname field
Please help me, Thank you so much!!
You will need to store the original input line somewhere. Also, you need to fix the indexing. First name is at index 1, not index 0 in your array. Finally, you do not need a \ before the comma in your regex.
I would recommend changing your map to store a list of all the lines for a first name in the value. The length of the list will provide you with the count you want. If you want the output to be sorted, you should also use a SortedMap such as TreeMap instead of HashMap:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Test1 {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
Map<String, List<String>> names = new HashMap<>();
File dir = new File("Data_File_In");
for (File file : dir.listFiles()) {
Scanner s = new Scanner(file);
s.nextLine();
while(s.hasNextLine()) {
String line = s.nextLine();
String[] actionID = line.split(",");
// String PFN = actionID[0].trim();
// String PLN = actionID[1].trim();
String name = actionID[1].trim();
if(!names.containsKey(name)) {
names.put(name, new ArrayList<String>());
}
names.get(name).add(line);
}
for(List<String> lines : names.values()) {
for(int i = 0; i < lines.size(); i++) {
System.out.println(lines.get(i) + "," + i);
}
}
s.close();
}
}
}
Related
I am working on an assignment in which the program needs to read a file located by user input.
The file is scanned and an array is created.
The array stores in words as strings and outputs how many times a word has been used.
Then, the output is printed out into a new file.
package TestFileReader;
import java.io.*;
import java.util.*;
public class ReadFile
{
public static void main(String[] args)
{
//Prompts user for file by asking for its location
Scanner keys = new Scanner(System.in);
String fileName;
System.out.print("Enter file location, or 'Quit' to quit: ");
fileName = keys.nextLine();
Scanner textFile = null;
//try catch block for exception
try
{
textFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException s)
{
System.out.println("File not found, confirm location: ");
}
//File will be read continuously until there is no next line
while(textFile.hasNextLine())
{
String contents = textFile.nextLine();
System.out.println(contents);
}
textFile.close();
//New Class for saving read into array
}
}
While I prepared the following example, Jan also answered properly that a HashMap can be used for this job:
HashMap<String,Integer> map=new HashMap<String,Integer>();
//File will be read continuously until there is no next line
while(textFile.hasNextLine())
{
String line = textFile.nextLine();
// Split line into words
String words[]=line.split("\\s+");
for (String word : words)
{
// Get current word count
Integer count=map.get(word);
if (count==null)
{
// Create a new counter for a new word
map.put(word,1);
}
else
{
// Increase existing word counter
map.put(word,count+1);
}
}
}
// Output result
for (Map.Entry<String,Integer> entry : map.entrySet())
{
System.out.println(entry.getKey()+": "+entry.getValue());
}
textFile.close();
The HashMap gets filled with an Integer counter for each word. If the word is found again, the counter will be increased. HashMaps are usually faster than nested loops over an array when you expect more than 20 entries.
Example inout file:
This is a test
This is another test
Wuff!
Example output:
a: 1
Wuff!: 1
test: 2
another: 1
This: 2
is: 2
Since Java 8 you could also use the Streams API to accomplish this task.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReadFile {
public static void main(String[] args) {
//Prompts user for file by asking for its location
Scanner keys = new Scanner(System.in);
String fileName;
System.out.print("Enter file location, or 'Quit' to quit: ");
fileName = keys.nextLine();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.flatMap(s -> Stream.of(s.split("\\W")))
.filter(s -> s != null && !s.isEmpty())
.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum))
.forEach((k, v) -> System.out.println(k + ": " + v));
} catch (IOException e) {
System.out.println("Cannot read file: " + fileName);
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need help with a method that finds a specific file and then prints out a line of text from that file. The line of text is printed if the string typed in the console matches a string from that line of text. For example if I were to call java Find ring report.txt address.txt Homework.java it should print something like:
report.txt: has broken up an internationa ring of DVD bootleggers that
address.txt: Kris Kringle, North Pole
address.txt: Homer Simpson, Springfield
Homework.java: String file name;
The specified word is always the first command line argument.
This is what I have so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Code for E11.8. Searches all files specified on the command line and prints out all lines
containing a specified word.
* #Michael Goedken
*/
public class Find
{
/**
Searches file for a word, prints out all lines containing that word.
#param wordToFind the word to find
#param filename the filename for the file to search
*/
public static void findAndPrint(String wordToFind, String filename)
{
String input = args[0];
for (int i = 1; i < args.length; i++)
{
System.out.println(" File " + args[i]);
File one = new File(args[i]);
Scanner in = new Scanner(one);
while (in.hasNext())
{
String line = in.nextLine();
if (line.contains(input))
{
System.out.println(line);
}
}
}
}
/**
First argument of the main method should be the word to be searched
For other arguments of the main method, store the file names to be examined
*/
public static void main(String[] args)
{
// call findAndPrint for each text file
}
}
You're trying to access the array args[] which is not in the scope of the function findAndPrint(). You need to pass args[0] as an argument to the function call statement in the main method:
public static void main(String[] args){
findAndPrint(args[0], args[1]); //for report.txt
findAndPrint(args[0], args[2]); //for address.txt
}
args is an argument of the main method. It is a String array that stores the individual command line inputs. In your case, the contents of the array args[] are = {"ring", "reports.txt", "address.txt", "Homework.java"}.
You can modify your findAndPrint() function in this way now:
static void findAndPrint(String wordToFind, String filename){
Scanner fscan = new Scanner(new File(filename));
String str = "";
while((str = fscan.nextLine()) != null){
if(str.contains(wordToFind))
System.out.println(str);
}
}
I've added main arguments. I haven't ran the code, so that's on you to debug and test.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Code for E11.8. Searches all files specified on the command line and prints out all lines containing a specified word.
* #Michael Goedken
*/
public class Find {
/** Searches file for a word, prints out all lines containing that word.
#param wordToFind the word to find
#param filename the filename for the file to search
*/
public static void findAndPrint(String wordToFind, String filename) {
System.out.println(" File " + filename);
File one = new File(filename);
Scanner in;
try {
in = new Scanner(one);
while (in.hasNext()) {
String line = in.nextLine();
if (line.contains(wordToFind)) {
System.out.println(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
int length = args.length;
if (length > 0 ) {
String wordToFind = args[0];
// now gather file names, bypassing first string
for (int ii = 1; ii < length; ii++) {
findAndPrint(wordToFind, args[ii]);
}
}
}
}
This seems to work as a solution!
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
/**
* Code for E11.8. Searches all files specified on the command line and prints out all lines
containing a specified word.
* #Michael Goedken
*/
public class Find
{
/**
Searches file for a word, prints out all lines containing that word.
#param wordToFind the word to find
#param filename the filename for the file to search
*/
public static void findAndPrint(String wordToFind, String filename) throws FileNotFoundException
{
Scanner in = new Scanner(new FileReader(filename));
String input = wordToFind;
while (in.hasNext())
{
String line = in.nextLine();
if (line.contains(input))
{
System.out.println(line);
}
}
}
/**
First argument of the main method should be the word to be searched
For other arguments of the main method, store the file names to be examined
*/
public static void main(String[] args) throws FileNotFoundException
{
// call findAndPrint for each text file
findAndPrint("tt", "/Users/MichaelGoedken/Desktop/mary.txt");
findAndPrint("0", "/Users/MichaelGoedken/Desktop/transactions.txt");
}
}
Ok, I think I get your issue now.
You can call your method from the main:
public static void main(String[] args) {
//may need to throw file not found exception here
findAndPrint();
}
Then you need to remove the arguments from your method:
public static void findAndPrint() throws FileNotFoundException {
Scanner in = new Scanner(new FileReader("C:\\yourfilepath\\actualfile.txt"));
//you can get user input etc here if necessary
String input = "pass";
while (in.hasNext()) {
String line = in.nextLine();
if (line.contains(input)) {
System.out.println(line);
}
}
}
Below is what the text document looks like. The first line is the number of elements that I want the array to contain. The second is the ID for the product, separated by # and the third line is the total price of the products once again separated by #
10
PA/1234#PV/5732#Au/9271#DT/9489#HY/7195#ZR/7413#bT/4674#LR/4992#Xk/8536#kD/9767#
153#25#172#95#235#159#725#629#112#559#
I want to use the following method to pass inputFile to the readProductDataFile method:
public static Product[] readProductDataFile(File inputFile){
// Code here
}
I want to create an array of size 10, or maybe an arrayList. Preferably to be a concatenation of Customer ID and the price, such as Array[1] = PA/1234_153
There you go the full class, does exactly what you want:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.io.IOException;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader inputFile = new BufferedReader(new FileReader("test.txt"));
String numberOfElements = inputFile.readLine();
//this is the first line which contains the number "10"
//System.out.println(numberOfElements);
String secondLine = inputFile.readLine();
//this is the second line which contains your data, split it using "#" as a delimiter
String[] strArray = secondLine.split("#");
//System.out.println(Arrays.toString(strArray));
//System.out.println(strArray[0]);
String thirdLine = inputFile.readLine();
//this is the third line which contains your data, split it using "#" as a delimiter
String[] dataArray = thirdLine.split("#");
//combine arrays
String[] combinedArray = new String[strArray.length];
for (int i=0;i<strArray.length;i++) {
combinedArray[i]=strArray[i]+"_"+dataArray[i];
System.out.println(combinedArray[i]);
}
}
}
OUTPUT:
PA/1234_153
PV/5732_25
Au/9271_172
DT/9489_95
HY/7195_235
ZR/7413_159
bT/4674_725
LR/4992_629
Xk/8536_112
kD/9767_559
The trick in what I am doing is using a BufferedReader to read the file, readLine to read each of the three lines, split("#"); to split each token using the # as the delimiter and create the arrays, and combinedArray[i]=strArray[i]+"_"+dataArray[i]; to put the elements in a combined array as you want...!
public static Product[] readProductDataFile(File inputFile){
BufferedReader inputFile = new BufferedReader(new FileReader(inputFile));
// the rest of my previous code goes here
EDIT: Everything together with calling a separate method from inside the main, with the file as an input argument!
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
File myFile = new File("test.txt");
readProductDataFile(myFile);
}
public static String[] readProductDataFile(File inputFile) throws FileNotFoundException, IOException{
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String numberOfElements = myReader.readLine();
//this is the first line which contains the number "10"
//System.out.println(numberOfElements);
String secondLine = myReader.readLine();
//this is the second line which contains your data, split it using "#" as a delimiter
String[] strArray = secondLine.split("#");
//System.out.println(Arrays.toString(strArray));
//System.out.println(strArray[0]);
String thirdLine = myReader.readLine();
//this is the third line which contains your data, split it using "#" as a delimiter
String[] dataArray = thirdLine.split("#");
//combine arrays
String[] combinedArray = new String[strArray.length];
for (int i=0;i<strArray.length;i++) {
combinedArray[i]=strArray[i]+"_"+dataArray[i];
System.out.println(combinedArray[i]);
}
return combinedArray;
}
}
OUTPUT
PA/1234_153
PV/5732_25
Au/9271_172
DT/9489_95
HY/7195_235
ZR/7413_159
bT/4674_725
LR/4992_629
Xk/8536_112
kD/9767_559
You don't even need the first line. Just read the second line directly into a single string and then split it by using String,split() method.
Read more for split method here.
You could use something like this (Be aware that i can't test it at the moment)
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("fileeditor.txt"));
String read = null;
String firstLine=in.readLine();
//reads the first line
while ((read = in.readLine()) != null) {
// reads all the other lines
read = in.readLine();
String[] splited = read.split("#");
//split the readed row with the "#" character
for (String part : splited) {
System.out.println(part);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
//close file
in.close();
} catch (Exception e) {
}
}
This is how you can do it using Java (don't forget to import):
public static Product[] readProductDataFile(File inputFile){
Scanner s = new Scanner(inputFile);
String data = "";
while(s.hasNext())
data += s.nextLine();
String[] dataArray = data.split("#");
}
You can try this way ..
Reading line by line and storing each row in a array.
Use while storing so it will split and save .
String[] strArray = secondLine.split("#");
Now use the for loop and concat the values as u wish and save ina third array .
For(int i=0 ;i< file.readline;i++)
{
string s = a[customerid];
s.concat(a[productid]);
a[k] =s;
}
How to list the files available in file system with the starting number and ending number?
like if there are 500 files in C:\Test\ then how to list files starting from 1 to 20 like
give start number and end number based on this list the files available for particular file path.
i am trying this in java
I tried some thing like this and it gives me all the files available for the given path
public static List<String> loadAllFiles(String filesLocation) {
//find OS
//String osName = System.getProperty("os.name");
//replace file path based on OS
filesLocation = filesLocation.replaceAll("\\\\|/", "\\"+System.getProperty("file.separator"));
List<String> pdfFiles = new ArrayList<String>();
if (log.isDebugEnabled()) {
log.debug("In loadAllFiles execute start");
}
File directoryList = new File(filesLocation);
File[] filesList = directoryList.listFiles();
try {
for (int count = 0; count < filesList.length; count++) {
if (!filesList[count].isDirectory() && filesList[count].getName().endsWith(SPLIT_AND_SAVE_WORKING_FILE_EXTENSION.trim())) {
// load only PDF files
pdfFiles.add(filesList[count].getName().replace(SPLIT_AND_SAVE_WORKING_FILE_EXTENSION.trim(), ""));
}
}
} catch (Exception filesException) {
filesException.printStackTrace();
//TODO : Log the exception
} finally {
if (filesList != null)
filesList = null;
if (directoryList != null)
directoryList = null;
}
log.debug("In loadAllFiles execute end");
return pdfFiles;
}
I think the question is misunderstood, Say if i have 1000 files[file names can be anything] and i want to restrict getting the files name like i will give starting Number and ending number. like 1 to 20 and i want to load those 20 files alone.
An example without external libraries using plain Java 7
import java.io.IOException;
import java.nio.file.DirectoryStream;
import static java.nio.file.DirectoryStream.Filter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
// list files starting with 1 till 20 "-.*"
public class FileNameFilter {
private static final Filter<Path> fileNameFilter = new Filter<Path>() {
#Override
public boolean accept(Path entry) throws IOException {
if (!Files.isRegularFile(entry)) {
return false;
}
return entry.getFileName().toString().matches("^([1][0-9]{0,1}|2[0]{0,1})-.*");
}
};
public static void main(String[] args) {
final String filesLocation = "resources/";
Path path = Paths.get(filesLocation);
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(path, fileNameFilter)) {
for (Path entry : dirStream) {
System.out.printf("%-5s: %s%n", "entry", entry.getFileName());
}
} catch (IOException e) {
// add your exception handling here
e.printStackTrace(System.err);
}
}
}
edit
a Java 8 version
// list files starting with 1 till 20 "-.*"
public class FileNameFilter {
public static void main(String[] args) {
final String filesLocation = "resources/";
try {
Files.walk(Paths.get(filesLocation))
.filter(p -> p.getFileName().toString().matches("^([1][0-9]{0,1}|2[0]{0,1})-.*"))
.forEach(entry -> {System.out.printf("%-5s: %s%n", "entry", entry.getFileName());});
} catch (IOException e) {
// add your exception handling here
e.printStackTrace(System.err);
}
}
}
edit 2
Examples to list the first 20 files in a directory.
note The order of the files is the same as you would run ls or dir in the directory.
Java 7 example
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileListLimiter {
private static final int MAX_FILES_TO_LIST = 20;
public static void main(String[] args) {
final String filesLocation = "resources/";
Path path = Paths.get(filesLocation);
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(path)) {
int fileCounter = 1;
for (Path entry : dirStream) {
System.out.printf("%-5s %2d: %s%n", "entry", fileCounter++, entry.getFileName());
if (fileCounter > MAX_FILES_TO_LIST) {
break;
}
}
} catch (IOException e) {
// add your exception handling here
e.printStackTrace(System.err);
}
}
}
Java 8 example
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileListLimiter {
private static final int MAX_FILES_TO_LIST = 20;
public static void main(String[] args) {
final String filesLocation = "resources/";
try {
Files.walk(Paths.get(filesLocation))
.filter(p -> p.toFile().isFile())
.limit(MAX_FILES_TO_LIST)
.forEach(entry -> {System.out.printf("%-5s: %s%n", "entry", entry.getFileName());});
} catch (IOException e) {
// add your exception handling here
e.printStackTrace(System.err);
}
}
}
Try something like
final String pattern = "^[1-20].*";
final FileFilter filter = new RegexFileFilter(pattern);
final File[] files = directory.listFiles(filter);
Starting from Java 7 you can take advantage of Files#walkFileTree . During visitFile you can use a regex to look for you specific file.
Something like this
Path start = Paths.get(filesLocation);
Final Pattern pattern = Pattern.compile("^([1]?[0-9]|[2][0])\\.pdf");
Files.walkFileTree(start, new SimpleFileVisitor<>()
{
#Override
public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs)
throws IOException
{
File f = filePath.toFile();
if (pattern.matcher().matches(f.getName())) {
System.out.println("Valid match found " + f.getName())
}
return FileVisitResult.CONTINUE;
}
});
why not use this logic. its pretty straight forward and you will not need any substitution or replacement.i assume that you will be able to convert this into code very easily into Java. i have not tested the regex but you get the basic idea.
1.use scanner(or any other way) to get the input ranges for the start and the end limit.
2.create a directory listing scanning every file in the directory. use a for loop here.
3.define a regular expression to fetch only the starting data for the file .
start pattern = (^[0-9]{0,2})[a-zA-Z].+[0-9]{0,2}$ use grouping in regular expression to fetch this group1
4.When you get the values from group1 check the file name if it starts with group1 data.
5 if this data falls in between the ranges that you want to search then create a arraylist and store the matched file in the arraylist.
6.carry on the process till end of the directory. The final arraylist would contain your files in the given ranges.
hope this helps
Not sure i fully understood your question, but here is a Java 8 example that iterates over files of a directory sorted by name, starting at a given offset and limiting the results to a given size. It also allows you to include/exclude directories from results.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class DirectoryWalkerTest {
public static void main(final String... args) throws IOException {
final String filesLocation = "/path/to/files";
System.out.println(getFiles(filesLocation, true, 0, 10));
System.out.println(getFiles(filesLocation, true, 10, 10));
System.out.println(getFiles(filesLocation, false, 0, 10));
System.out.println(getFiles(filesLocation, false, 10, 10));
}
/**
* Returns a limited list of filenames starting at the given offset.
*
* #param filesLocation the directory to scan
* #param filterDirectories should we include directories in results
* #param offset the starting offset
* #param limit the maximum number of results
* #return a collection of file names
*/
private static Collection<String> getFiles(final String filesLocation, final boolean filterDirectories,
final int offset, final int limit) throws IOException {
Stream<Path> stream = Files.list(Paths.get(filesLocation));
if (filterDirectories) {
stream = stream.filter(path -> !Files.isDirectory(path));
}
return stream
.map(Path::toString)
.sorted()
.skip(offset)
.limit(limit)
.collect(Collectors.toList());
}
}
Based on your code, you could try this :
int begin = 0;
int limit = 10;
for (int count = 0; count < filesList.length; count++)
{
if (!filesList[count].isDirectory() && filesList[count].getName().endsWith(SPLIT_AND_SAVE_WORKING_FILE_EXTENSION.trim()))
{
// moving to begin index, only if the file is not a directory and is matching your criteria, whatever it is
if (count < begin) continue;
// load only PDF files
pdfFiles.add(filesList[count].getName().replace(SPLIT_AND_SAVE_WORKING_FILE_EXTENSION.trim(), ""));
}
// Stopping when limit is reached
if (pdfFiles.size() == limit) break;
}
It will move to begin index and get limit items, based on your criteria.
I played around with it and came up with something that works for me. Perhaps you can find the parts you need. If you don't want the full path, just remove the getCanonicalPath().
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
public class GetFirst_20_pdf_files {
// Creating an empty array list with 10 entries (the default)
ArrayList<String> pdfFiles = new ArrayList<String>();
public ArrayList<String> myList() {
// here you can get start and end from user
int start = 2;
int end = 4;
// and set the directory
String filesLocation = ".";
File directoryList = new File(filesLocation);
File[] files = directoryList.listFiles();
int count = 0;
for (File file : files) {
// don't want directories
if (file.isDirectory()) { continue; }
// want ".pdf" files only
if (!file.getName().toLowerCase().endsWith(".pdf")) { continue; }
// only want between start and end
count++;
if (count >= start && count <= end) {
try {
pdfFiles.add(file.getCanonicalPath());
} catch (IOException e) {
System.out.println(e);
}
if (count >= end) { return pdfFiles; }
}
}
return pdfFiles;
}
public static void main(String[] args) throws IOException {
GetFirst_20_pdf_files L = new GetFirst_20_pdf_files();
ArrayList<String> aList = L.myList();
for (String p : aList) {
System.out.println(p);
}
}
}
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.ArrayList;
/**
* Write a description of class ReadInCsv here.
*
* #author (Kevin Knapp)
* #version (10-10-2013)
*/
public class ReadInCsv
{
public static void main(String[] args)
{
String csvName = "Countries.csv";
File csvFile = new File(csvName);
ArrayList<String> nameList = new ArrayList<>();
ArrayList<String> popList = new ArrayList<>();
ArrayList<String> areaList = new ArrayList<>();
ArrayList<String> gdpList = new ArrayList<>();
ArrayList<String> litRateList = new ArrayList<>();
try
{
Scanner in = new Scanner(csvFile).useDelimiter(",");
while (in.hasNext())
{
String name = in.next();
nameList.add(name);
String pop = in.next();
popList.add(pop);
String area = in.next();
areaList.add(area);
String gdp = in.next();
gdpList.add(gdp);
String litRate = in.next();
litRateList.add(litRate);
}
in.close();
System.out.println(nameList);
System.out.println(popList);
System.out.println(areaList);
System.out.println(gdpList);
System.out.println(litRateList);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
So im trying to read from a csv file and as it goes through it should add each scanned instance into a array list (im going to reference each element from these lists at a later point), but my outputs show that as soon as it reads something and adds it, it skips to the next line before reading the next string, i need it to read straight across, not diagonally
im sure im just missing something very simple, I just began learning java about a week ago, thanks for the help
A big problem with this method is that unless each line in the file ends in a comma, newlines will not be delimited. A better way is to read each line in, split on commas, and add the values to the ArrayLists one line at a time:
Scanner in = new Scanner(csvFile);
while (in.hasNextLine()) {
String[] fields = in.nextLine().split(",");
if (fields.length == 5) {
nameList.add(fields[0]);
popList.add(fields[1]);
areaList.add(fields[2]);
gdpList.add(fields[3]);
litRateList.add(fields[4]);
} else {
// Bad line...do what you want to show error here
}
}
An even better way is to use a Java library dedicated to reading CSV files. A quick Google search should turn up some good ones.