Multiple Over writes using FileWriter in Java - java

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);

Related

Splitting Contents of a File

So I have a file with a list of users in the format like this:
michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash
abigail:&i4KZ5wmac566:501:501:Abigail Smith:/home/abigail:/bin/tcsh
What I need to do is just extract the passwords from the file which in this case are:
"atbWfKL4etk4U" and "&i4KZ5wmac566" and to store them into an array.
This is what I have so far:
public static void main(String[] args) throws IOException{
// Create a scanner for keyboard input
Scanner scan = new Scanner(System.in);
// Prompt user to select a file to open
System.out.print("Enter the path of the file: ");
String filename = scan.nextLine();
// Open the file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Create Array to store each user password in
String[] passwords = {};
// Close the file
scan.close();
inputFile.close();
}
public static void main(String[] args) throws IOException{
// Create a scanner for keyboard input
Scanner scan = new Scanner(System.in);
// Prompt user to select a file to open
System.out.print("Enter the path of the file: ");
String filename = scan.nextLine();
// Open the file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
List<String> passwords = new ArrayList<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String password = line.split(":")[1];
passwords.add(password);
}
// Close the file
scan.close();
inputFile.close();
}
If instead you rather store username and password (assuming the first token is the user name), create a Map instead of a List.
Map<String, String> passwordMap = new HashMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] tokens = line.split(":");
passwordMap.put(tokens[0], tokens[1]);
}
You could read the file line by line using a Scanner object.
Then, you use another Scanner object to read the password. Here's an example:
String input = "michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash";
Scanner s = new Scanner(input).useDelimiter(":");
s.next(); //skipping username
String password = s.next();
This looks like a typical CSV type file format and because there is an unknown number of Users in the file and the fact that arrays can not dynamically grow it's a good idea to utilize an ArrayList which can grow dynamically and then convert that list to a String array, for example:
The following method assumes there is No Header Line within the data file:
public static String[] getPasswordsFromFile(String filePath) {
List<String> passwordsList = new ArrayList<>();
File file = new File(filePath);
try (Scanner reader = new Scanner(file)) {
String line = "";
while (reader.hasNextLine()) {
line = reader.nextLine().trim();
// Skip blank lines (if any).
if (line.isEmpty()) {
continue;
}
/* Split out the password from the file data line:
The Regular Expression (RegEx) below splits each
encountered file line based on the Colon(:) delimiter
but also handles any possible whitespaces before
or after that delimiter: */
String linePassword = line.split("\\s*\\:\\s*")[1];
// If there is no password there then apply "N/A":
if (linePassword.isEmpty()) {
linePassword = "N/A";
}
// Add the password to the List
passwordsList.add(linePassword);
}
}
catch (FileNotFoundException ex) {
// Handle the exception (if any) the way you like...
System.err.println(ex.getMessage());
}
// Convert the List<String> to String[] Array and return:
return passwordsList.toArray(new String[passwordsList.size()]);
}
How you might use a method like this:
// Create a scanner object for keyboard input
Scanner userInput = new Scanner(System.in);
// Prompt user to select a file to open with validation:
String fileName = "";
// -----------------------------------
while (fileName.isEmpty()) {
System.out.print("Enter the path of the file (c to cancel): --> ");
fileName = userInput.nextLine();
if (fileName.equalsIgnoreCase("c")) {
System.out.println("Process Canceled! Quiting.");
System.exit(0);
}
if (!new File(fileName).exists()) {
System.out.println("Invalid Entry! Try again...\n");
fileName = "";
}
}
// -----------------------------------
/* OR - you could have........
// -----------------------------------
javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new File("").getAbsolutePath());
fc.showDialog(new JDialog(), "get Passwords");
if (fc.getSelectedFile() != null) {
fileName = fc.getSelectedFile().getAbsolutePath();
}
else {
System.out.println("Process Canceled! Quiting.");
System.exit(0);
}
// -----------------------------------
*/
// Get the Passwords from file:
String[] passwords = getPasswordsFromFile("UserData.txt");
// Display the Passwords retrieved:
System.out.println();
System.out.println("Passwords from file:");
System.out.println("====================");
for (String str : passwords) {
System.out.println(str);
}
If you were to run this code against a file which contains the data you provided within your post,your console window will diplay:
Enter the path of the file (c to cancel): --> userData.txt
Passwords from file:
====================
atbWfKL4etk4U
&i4KZ5wmac566

File read but won't print contents

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));

FileWriter and PrintWriter won't output to file

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.

PrintWriter program

Im trying to write a program that will ask for the name of an input file and an output file. It will open the input file and create the output file. It will then read the input file and make a double-spaced copy of the input in the output file.
public class ProgramTest
public static void main (String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("where to read?");
String in = keyboard.nextLine();
System.out.println("where to write?");
String out = keyboard.nextLine();
Scanner scanner = new Scanner(new File(in));
PrintWriter outputFile = new PrintWriter(out);
}
Thats what I have so far. What I dont know is how to make it do the last part to read the input file and make a double-spaced copy of the input in the output file.
well you can start by reading in the file?
private static void readFile(String inputFile) {
File file = new File(inputFile);
try {
Scanner scan = new Scanner(file);
//for example String s = scan.next(); would store next word
//doulbe d = scan.nextDouble(); would grab next double
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Once you read in the file sore the lines/numbers into variables?? Should not be to hard work with the read file i provided. Also remember what should you read in first ints or strings?

How to capture the file name from the server dynamically when some one uploads it

Below is the code to read the file from the server. I Want to read & convert the file dynamically (not hard coded )into different file format(CSV). Could anyone please guide me to capture the uploaded file name dynamically.
try
{
//creating File instance to reference text file in Java
String str1=null;
String str2=null;
String str3=null;
int cnt=0,len1=0,len2=0;
File text = new File("C:\\Petty Ascii Detail.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
File file = new File("C:\\Test\\Write1.txt");
//if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
//Reading each line of file using Scanner class
int lineNumber = 1;
while(scnr.hasNextLine())
{
String line = scnr.nextLine();
cnt=line.length();
for(int i=0;i<3;i++)
{
if (Character.isDigit(line.charAt(i)))
str1=line;
else
str2=line;
}
len1=str1.length();
len2=str2.length();
if(len1!=len2)
{
str3=str1+str2;
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(str3);
bw.newLine();
System.out.println("Done");
bw.close();
}
lineNumber++;
}
}
catch (IOException e)
{
e.printStackTrace();
}
Any suggestions are really appreciated.
Thanks,
Balaji

Categories

Resources