The program takes in one file at a time from the command line and executes it.
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine())
{
fileName = scan.nextLine();
File xmlFile = new File(fileName);
// Do SOMETHING with xmlFile
}
Basically I want to take a list of files from the commandlines unless the user does CTRL+D.
How do i change it?
An alternative to using a Scanner would be to use a stream:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
Stream lines = br.lines();
Consumer processFile = new Consumer() {
public void accept(Object o) {
File xmlFile = new File(o.toString());
// Do SOMETHING with xmlFile
}
};
lines.forEach(processFile);
Ctrl+D is end-of-stream so it'll just take you out of the loop.
List<String> fileList = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine())
{
line = scan.nextLine();
if(line.equals("-1"){
break;
}
fileList.add(line);
}
for(String file: fileList){
File xmlFile = new File(file);
//process
}
Else keep doing as per your original code and use CTRL+C to exit the VM.
Pass files as argument like below :
java XYZClass file1.csv file2.csv
and access that in your code like below ;
URL url = getClass().getResource(args[0]);
File myFile = new File(url.getPath());
InputStream input = new FileInputStream(myFile);
Related
I wanted to ask how I can load information of a csv-file in a list. I don't have much until now so a little help would be nice if possible. What I tried until now is to get the file but I'm not sure if it's right because I'm not that good at File I/O. After that I stuck at how to save it in a list.
List<GameCharacter> characters;
static void loadTextFile(String textFile) throws FileNotFoundException {
//textFile = String.valueOf(new File("C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv"));
textFile = "C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv";
FileInputStream d = new FileInputStream(textFile);
}
Not sure if you have any limitations on what you can use and what can't but did you try using OpenCSV library?
You can then read it like this
try (CSVReader reader = new CSVReader(new FileReader("file.csv"))) {
List<String[]> r = reader.readAll();
r.forEach(x -> System.out.println(Arrays.toString(x)));
}
This will give you a list of array of strings which will contain all the values for each line.
You can use Scanner like this
textFile = "C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv";
List<List<String>> mylist = new ArrayList<>();
try (Scanner scanner = new Scanner(new File("textFile"));) {
while (scanner.hasNextLine()) {
mylist.add(getRecordFromLine(scanner.nextLine()));
}
}
You can also use BufferedReader in java.io like the following
textFile = "C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv";
List<List<String>> myList = new ArrayList<>();
try (BufferedReader bffuerReader = new BufferedReader(new FileReader("textFile"))) {
String line;
while ((line = bffuerReader.readLine()) != null) {
String[] values = line.split(COMMA_DELIMITER);
myList.add(Arrays.asList(values));
}
}
The user can select a file to be scanned, however none of the file's contents are printed at run-time, any help?
public void readVehicleData(){
FileDialog fileBox = new FileDialog(mainWindow,"Open", FileDialog.LOAD);
fileBox.setVisible(true);
fileBox.setDirectory(".");
String dataFile = fileBox.getFile();
Scanner scanner = new Scanner(dataFile);
while( scanner.hasNext() )
{
String lineOfInput = scanner.nextLine();
System.out.println(lineOfInput);
}
scanner.close();
}
Use the constructor that accepts a File rather than a String as its InputStream source
Scanner scanner = new Scanner(new File(dataFile));
I have this code
public User createnewproflie() throws IOException
{
FileWriter fwriter = new FileWriter("users.txt",true); //creates new obj that permits to append text to existing file
PrintWriter userfile = new PrintWriter(fwriter); //creates new obj that prints appending to file as the arg of the obj is a pointer(?) to the obj that permits to append
String filename= "users.txt";
Scanner userFile = new Scanner(filename); //creates new obj that reads from file
User usr=new User(); //creates new user istance
String usrname = JOptionPane.showInputDialog("Please enter user name: "); //acquires usrname
userfile.println("USER: "+usrname+"\nHIGHSCORE: 0\nLASTPLAY: 0"); //writes usrname in file
userfile.flush();
usr.setName(usrname); //gives usr the selected usname
return usr;
}
and it doesn't output on the file... can someone help please?
i knew that flush would output all of the buffered text but it doesn't seem to work for some strange reason...
You can use a String with a FileWriter but a Scanner(String) produces values scanned from the specified string (not from a File). Pass a File to the Scanner constructor (and it's a good idea to pass the same File to your FileWriter). And you need to close() it before you can read it; maybe with a try-with-resources
File f = new File("users.txt");
try (FileWriter fwriter = new FileWriter(f,true);
PrintWriter userfile = new PrintWriter(fwriter);) {
// ... Write stuff to userfile
} catch (Exception e) {
e.printStackTrace();
}
Scanner userFile = new Scanner(f);
Finally, I usually prefer something like File f = new File(System.getProperty("user.home"), "users.txt"); so that the file is saved in the user home directory.
Im trying to read N different CSV files containing stock price data. I want to extract one particular column from each file and showcase those columns in a single CSV file.
The issue is the combined file contains only the written data from the first file I give as input i.e. that data is not being overwritten in the iteration of my loop.
Can someone help? Or suggest a new method?
public static void main(String[] args) throws IOException
{
int filecount=0;
System.out.println("Enter Number of Files");
Scanner stream =new Scanner(new InputStreamReader(System.in));
filecount= Integer.parseInt(stream.next());
File file2 = new File("Combined_Sym.csv");
FileWriter fwriter= new FileWriter("Combined_Sym.csv",true);
PrintWriter outputFile= new PrintWriter(fwriter);
int i;
for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
File file = new File(fileName);
Scanner inputStream = new Scanner(file);
Scanner inputStream2= new Scanner(file2);
if(!inputStream2.hasNext()){
outputFile.println(fileName);
}
else
{ String header=inputStream2.next();
System.out.println(header+","+fileName);
outputFile.println(header+","+fileName);
}
while(inputStream.hasNext())
{
String data= inputStream.next();
String[] values = new String[8];
values = data.split(",");
String sym=values[7];
if(!inputStream2.hasNext())
outputFile.println(sym);
else
{
String data2= inputStream2.next();
outputFile.println(data2+","+sym);
System.out.println(data2+","+sym);
}
}
inputStream.close();
inputStream2.close();
outputFile.close();
}
}
}
Can you try changing :
for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
File file = new File(fileName);
to
File file;
for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
file = new File(fileName);
Most examples out there on the web for inputting a file in Java refer to a fixed path:
File file = new File("myfile.txt");
What about a user input file from the console? Let's say I want the user to enter a file:
System.out.println("Enter a file to read: ");
What options do I have (using as little code as possible) to read in a user specified file for processing. Once I have the file, I can convert to string, etc... I'm thinking it has to do with BufferedReader, Scanner, FileInputStream, DataInputStream, etc... I'm just not sure how to use these in conjunction to get the most efficient method.
I am a beginner, so I might well be missing something easy. But I have been messing with this for a while now to no avail.
Thanks in advance.
To have the user enter a file name, there are several possibilities:
As a command line argument.
public static void main(String[] args) {
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
}
By asking the user to type it in:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
Use a java.io.BufferedReader
String readLine = "";
try {
BufferedReader br = new BufferedReader(new FileReader( <the filename> ));
while ((readLine = br.readLine()) != null) {
System.out.println(readLine);
} // end while
} // end try
catch (IOException e) {
System.err.println("Error Happened: " + e);
}
And fill the while loop with your data processing.
Regards,
Stéphane