I need to rename the file temp.txt later on in my code. I tried doing this with the newFile = new File(name); line, but this just created a new file entirely. Could you point me in the right direction here?
public static File InputOutput (Scanner console, int in_Out) throws
FileNotFoundException {
//<editor-fold>
String name = "newName";
String line = "";
String in_OutText = "";
File newFile = new File("temp.txt");
for (int i = 0; i <= in_Out; i++) {
if (i == 0) {
in_OutText = "Input";
} else {
in_OutText = "Output";
}
System.out.print(in_OutText + " file name: ");
name = console.next();
if (i == 1) {
newFile = new File(name);
}
}
PrintStream inputCopy = new PrintStream(newFile)
Scanner input = new Scanner(name);
while (input.hasNextLine()) {
line = input.nextLine();
inputCopy.println(line);
inputCopy.println("WORKED");
}
return newFile;
}
Thanks!
Related
I'm trying to prompt the user to input the name a file they'd like to write to, create that .txt file and then write the qualifying lines of text into that file and save it. inside the do while, it seems to be skipping over the user input for the name of the file they'd like to save to, looping back around and then getting a FileNotFoundException, and it shouldn't even be looking for a file.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I just needed to skip a line before the loop began.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
user.nextLine(); //SOLUTION HERE
do {
System.out.println("please enter a name for the file to write to (end with .txt): ");
String out = user.nextLine();
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0], Integer.parseInt(elements[1]), Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]), Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost && bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
So i have this code and i'm having trouble retrieving data from my csv file and putting them into an array.
This is what i have on my CSV file
D001,55,Lab,Butch
D002,22,Husky,Ben
D003,12,Maltese,John
D004,34,GermanSheperd,James
D005,76,Rot,Smith
public static void CSVInputFile() throws IOException {
FileReader inFileReader;
BufferedReader in;
String inStr;
File myFile;
String dogID;
int size;
String breed;
String name;
myFile = new File("DogFile.csv");
inFileReader = new FileReader(myFile);
in = new BufferedReader(inFileReader);
inStr = in.readLine();
Dog[] NewReadDog = new Dog[5];
int i = 0;
while (inStr != null) {
StringTokenizer dogTok = new StringTokenizer(inStr, ",");
while (dogTok.hasMoreTokens()) {
dogID = dogTok.nextToken();
size = new Integer(dogTok.nextToken());
breed = dogTok.nextToken();
name = dogTok.nextToken();
NewReadDog[i] = new Dog(dogID, size, breed, name);
i++;
System.out.println("dog " + i + " is stored");
}
}
System.out.println("\nOutput Dogs from CSV FILE: ");
for (int count = 0; count < NewReadDog.length; count++) {
System.out.println(NewReadDog[count]);
}
in.close();
}
I'm just starting to learn coding so please bear with me.
thanks
You have to read the next line when finished tokenizing the current one:
while (inStr != null) {
StringTokenizer dogTok = new StringTokenizer(inStr, ",");
while (dogTok.hasMoreTokens()) {
[...]
}
System.out.println("dog " + i + " is stored");
inStr = in.readLine();
i++; //replaced here
}
I've been trying to fill an array with strings & break it into different arrays, but i must not be reading it in right because my array has nothing in it?
File inf = FileUtil.openFile(args); // open the file passedin in args
Scanner fin = new Scanner(inf);
public static File readFileInfo(Scanner kb)throws FileNotFoundException
{
String fileName = null;
File inFile = null;
do
{
System.out.print("Enter the name of the input file: ");
fileName = kb.nextLine();
inFile = new File(fileName);
}while(!inFile.exists());
return inFile;
}// end readFileInfo
public static Author[] fillArray(Scanner fin)
{
Author[] array = new Author[100];
String first_ = null;
String last_ = null;
String publisher_ = null;
int x = 0;
while(fin.hasNext())
{
first_ = fin.nextLine();
last_ = fin.nextLine();
publisher_ = fin.nextLine();
Author temp = new Author(first_, last_, publisher_);
array[x] = temp;
x++;
}
return array;
Maybe the problem is that you check if you have one more token but try to fetch three tokens
while(fin.hasNext()) // CHECK IF WE HAVE ONE MORE TOKEN
{
first_ = fin.nextLine(); // FETCH THREE
last_ = fin.nextLine();
publisher_ = fin.nextLine();
Author temp = new Author(first_, last_, publisher_);
array[x] = temp;
x++;
}
This may have lead to an exception, and the empty array.
This is a program to read a file and print out the file with some of the text edited. The code will compile the issue is that it will read the users input but will say file is not found when the file is there. I feel like I am missing something. I am brand new at this so go easy on me.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MainTest {
public static void main(String args[]) {
// if (args[0] != null)
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = "";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count;
} else if (ch == '}') {
out = out + " " + count;
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}
You can use System.getProperty("user.dir") to find where Scanner looking to find your file. And you should be sure your file is located here.
So the following program should take in an input and output file as command line arguments.
class FileCopy
{
public static void main(String[] args) throws IOException
{
String infile = null;
String outfile = null;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
if (args.length >= 2) //both files given via command line
{
infile = args[0];
if (fileExists(infile) == false)
{
infile = getInputFile();
}
outfile = args[1];
}
else if (args.length == 1) //input file given via command line
{
infile = args[0];
outfile = getOutputFile(infile);
}
else //no files given on command line
{
infile = getInputFile();
outfile = getOutputFile(infile);
}
//create file objects to use
File in = new File(infile);
File out = new File(outfile);
/*
*rest of code
*/
}
//get the input file from the user if given file does not exist
public static String getInputFile() //throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
boolean haveFile = false;
while(haveFile == false)
{
System.out.println("Enter a valid filename for input:");
System.out.print(">> ");
try
{
fileName = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
haveFile = fileExists(fileName);
}
return fileName;
}
//get the output file and test things
public static String getOutputFile(String infile)
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
File input = new File(infile);
String filename = null;
boolean more = true;
while(more)
{
System.out.println("Enter a valid filename for output:");
System.out.print(">> ");
try
{
filename = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
File output = new File(filename);
if (output.exists())
{
more = false;
}
if (filename == infile)
{
int selection;
String inputString = null;
System.out.println("The output file given matches the input file. Please choose an option:");
System.out.println("1) Enter new filename");
System.out.println("2) Overwrite existing file");
System.out.println("3) Backup existing file");
System.out.print(">> ");
try
{
inputString = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
selection = Integer.valueOf(inputString);
switch (selection)
{
case 1: //new filename
case 2: //overwrite
case 3: //backup
default: System.exit(0);
}
}
}
return null;
}
//check the given file to see if it exists in the current working directory
public static boolean fileExists(String n)
{
return (new File(n)).exists();
}
}
One detail that I believe you have missed:
When your program has only one argument (args.length == 1), i.e. when only the input file is defined, fileExists() is not called at all; infile is set to args[0] with no validation at all. You should probably add a specific check as you have done for the two-argument case.
I've ran into a similar problem too. I was working under eclipse, and had to specify "src/file.txt" with my current directory having a file named "file" in the src directory.
Note: It was not named "file.txt" (this causes the string to be interpreted as "file.txt.txt"!).
Try testing against this program here assuming you have a file named "file" in your "src" directory:
import java.io.File;
public class FileChecker {
public static boolean Exists( String file )
{
System.out.println("File being checked: " + file);
return( (file.length()) > 0 && (new File(file).exists()) );
}
public static void main( String[] args )
{
File dir = new File("src");
System.out.println("List of files in source directory: ");
if( dir.isDirectory()){
File[] filenames = dir.listFiles();
for( Object file : filenames ) {
System.out.println(file.toString());
}
}
else
System.out.println("Directory does not exist.");
if(FileChecker.Exists("src/file.txt"))
System.out.println("File exists");
else
System.out.println("File does not exist");
}
}
It will print out the current files in source directory so you can see whether the file is really there or not, then you can test if it actually exists. Works on my end.