i am having some problem in java, i wanted to remove number 5 to number 7 and save them into a new file called RevisedNumbers.txt, is there any way to do that? this is my code so far
import java.util.Scanner;
import java.io.*;
public class Txt {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File myObj = new File("Numbers1to10.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
try {
Writer writer = new PrintWriter("Numbers1to10.txt");
for(int i = 1; i <= 10; i++)
{
writer.write("Number" + i);
writer.write("\r\n");
}
writer.close();
File readFile = new File("Numbers1to10.txt");
Scanner read = new Scanner(readFile);
while (read.hasNextLine())
System.out.println(read.nextLine());
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
try {
File myObj = new File("RevisedNumbers.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
the desired output on the new file will be
Number 1
Number 2
Number 3
Number 4
Number 8
Number 9
Number 10
One possible solution might be using an additional file.
While reading the contents of the first file ("Numbers1to10.txt"), if values are within 5 to 7, then write it into the second file ("RevisedNumbers.txt"), otherwise write it into the additional file.
Now the additional file contains values that you need in the first file. So copy all contents of the additional file into the first file.
Here is a sample code.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileWriteMain {
static void _write1to10(String locationWithFileName) {
try {
File file = new File(locationWithFileName);
boolean fileAlreadyExist = file.exists();
if (fileAlreadyExist) {
System.out.println("File already exists!");
} else {
System.out.println("New file has been created.");
}
FileWriter fileWriter = new FileWriter(file);
for (int i = 1; i <= 10; i++) {
fileWriter.write("Number " + i);
fileWriter.append('\n');
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static File _getFile(String locationWithFileName) {
File file = null;
file = new File(locationWithFileName);
return file;
}
// it reads a file and print it's content in console
static void _readFile(Scanner scanner) {
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
System.out.println(currLine);
}
}
// read contents from sourceFile file and copy it into destinationFile
static void _copyFromOneFileToAnother(File sourceFile, File destinationFile) throws IOException {
FileWriter destFileWriter = new FileWriter(destinationFile);
Scanner scanner = new Scanner(sourceFile);
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
destFileWriter.write(currLine);
destFileWriter.append('\n');
}
destFileWriter.close();
}
public static void main(String[] args) {
String locationWithFileName = "E:\\FileWriteDemo\\src\\Numbers1to10.txt"; // give your file name including it's location
_write1to10(locationWithFileName);
System.out.println("File writing done!");
File file1 = _getFile(locationWithFileName);
try {
// creating file 2
String locationWithFileName2 = "E:\\FileWriteDemo\\src\\RevisedNumbers.txt";
File file2 = _getFile(locationWithFileName2);
FileWriter fileWriter2 = new FileWriter(file2);
// creating a temporary file
String tempFileLocationWithName = "E:\\FileWriteDemo\\src\\temporary.txt";
File tempFile = _getFile(tempFileLocationWithName);
FileWriter tempFileWriter = new FileWriter(tempFile);
Scanner scanner = new Scanner(file1);
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
// split the word "Number" from integer
String words[] = currLine.split(" ");
for (int i = 0; i < words.length; i++) {
// System.out.println(words[i]);
try {
int num = Integer.parseInt(words[i]);
if (num >= 5 && num <= 7) {
// writing to second file
fileWriter2.write(currLine);
fileWriter2.append('\n');
} else {
// writing to temporary file
tempFileWriter.write(currLine);
tempFileWriter.append('\n');
}
} catch (NumberFormatException e) {
// current word is not an integer, so don't have to do anything
}
}
}
fileWriter2.close();
tempFileWriter.close();
_copyFromOneFileToAnother(tempFile, file1);
System.out.println("\nContents of first file");
_readFile(new Scanner(file1));
System.out.println("\nContents of second file");
_readFile(new Scanner(file2));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope it helps!
Happy coding.
I am running JUnit tests on a method checkFile(), the method is supposed to check a file for some values and prompt the user when the values in the file are not permissible for a new file. If the file is ok, the method returns a value.
The problem is my test fails due to a StackOverflow error each time and never actually runs. The error points to the scanner object I am using to access the file.
I think the issue may be related to my use of recursion in the method but I cannot think of any other way to do this without writing redundant code if I don't use recursion.
Fyi, I know I could break this method into smaller methods but this assignment requires that I do not create any additional methods. I have tried to use BufferedReader Reader = new BufferedReader ( new FileReader(file))
also but the same issue occurs.
Fyi , line 137 in the Simulator class is where I instantiate the object Scanner Reader = new Scanner(file);
public ArrayList<Customer> checkFile(int stops, File file) {
Simulator sim = new Simulator();
int linesProcessed = 0;
String customerdata = " ";
String[] dataArray;
int[] parsedVals = new int[4];
String delimiter = " ";
List<Customer> custList = new ArrayList<Customer>();
List idArray = new ArrayList();
try {
Scanner Reader =new Scanner(file);//--> this appears to be causing the issue.
while (Reader.hasNextLine()) {
customerdata = Reader.nextLine();
dataArray = customerdata.split(delimiter);
for (int i = 0; i < dataArray.length; i++) {
try {
parsedVals[i] = Integer.parseInt(dataArray[i]);
if (parsedVals[i] <=0 ){
System.out.println("file input 0");
throw new IllegalArgumentException();
}
if (i==2 | i==3 ){
if(parsedVals[i]>stops){
throw new IllegalArgumentException();
}
}
} catch (NumberFormatException ex) {
if (linesProcessed == 0) {
System.out.println("Each line must have four integers. Try again.");
} else {
System.out.println(" Regular:Data in input file is not correct. Try again.");
}
sim.getInputFile();
sim.checkFile(stops, file);
}
catch(IllegalArgumentException args){
System.out.println("Data in input file is not correct. Try again.");
file =sim.getInputFile();
custList = sim.checkFile(stops, file);
}
}
try{
if(parsedVals[2]==parsedVals[3]) {
throw new IllegalArgumentException();
}
custList.add(new Customer(parsedVals[0], parsedVals[1], parsedVals[2], parsedVals[3]));
}catch(IllegalArgumentException ex){
System.out.println("Data in input file is not correct. Try again.");
file =sim.getInputFile();
custList = sim.checkFile(stops, file);
}
idArray.add(linesProcessed, parsedVals[0]);
linesProcessed++;
}
boolean duplicates = false;
for (int j = 0; j < idArray.size(); j++) {
for (int k = j + 1; k < idArray.size(); k++) {
if (k != j && idArray.get(k) == idArray.get(j)) {
duplicates = true;
}
}
}
if (duplicates) {
System.out.println(" Duplicates: Data in input file is not correct. Try again.");
File newfile = sim.getInputFile();
sim.checkFile(stops, newfile);
}
}
catch (FileNotFoundException ex) {
System.out.println("File not found, try again.");
file = sim.getInputFile();
sim.checkFile(stops, file);
}
return custList;
}
There are many tests but all the tests essentially do something similar. See bellow :
I'm almost there, but I'm getting an error to delete a catch for exceptions. Second to the last line of code. Also is there any way to only choose specific spots on the array to print out to the text file? Thanks
import java.io.*;
import java.util.*;
public class Project_Space
{
public static void main(String[] args)
{
// 2D Array of Passengers and Pilots objects- the Passengers class is in the Person.java file
Person[][] Members ;
int num_flights= 6; //create the "x" bound/size of the array
int num_passengers= 9; //create the "y" bound/size of the array
Members = new Person[num_flights][num_passengers];
//The Members array at index 0 is the first company
Members[0][0] = new Person.Flight(1); //This spot in the array is for the Company number in the first spot. Everything else are place holders for data that doesn't pertain to the company
Members[0][1] = new Person.Pilots(1,"1877963200","Amadeus","Durrutti","Buckminster Cornwallis","1288211435", 11); //This spot in the array is for the first team member of company #1
Members[0][2] = new Person.Pilots(2,"6054350085","Sirius","Sassafrass","Ali Bababa","1776812631", 9);
Members[0][3] = new Person.Passengers(1,"7065253333","Amy","Hartman","Betty Sue","7708889999", 3, 50000,"0554055405540554");
Members[0][4] = new Person.Passengers(2,"7545251337","Amanda","Zion","Beatrice Twix","7448656577", 4, 2000,"0554055405541111");
Members[0][5] = new Person.Passengers(3,"8904448899","Janet","Graves","Neal Wade","4445556666", 5, 3000, "9031029266161432");
Members[0][6] = new Person.Passengers(4,"8902234567","Kristen","Pickering","Christopher Soto","5685461208", 6, 51500, "0985028135114275");
Members[0][7] = new Person.Passengers(5,"5000893778","Julianna","Estrada","Jill Hansen","2770779833", 7, 0, "0213595590286251");
Members[0][8] = new Person.Passengers(6,"2080670437","Regena","Mckenzie","Vicki Cook","6224215759", 8, 250, "8204699533830238");
....
Arrays.deepToString(Members);
PrintWriter writer;
try
{
writer = new PrintWriter("flightnames.txt");
for (int i = 0; i<Members.length; i++){
for(int j = 0; j<Members.length; j++){
writer.print(Members[i][j] + ",");
}writer.println();
}}
catch (FileNotFoundException e){
System.out.println("Error: " + e.getMessage());
}
finally{if (writer!=null)
writer.close();
catch (Exception e)
{System.out.println("Could not close writer");}
}
}
}
Move your finally block, and it should compile properly. For the future use an IDE and use formatting, it will show you your mistakes faster:)
Arrays.deepToString(Members);
PrintWriter writer;
try {
writer = new PrintWriter("flightnames.txt");
for (int i = 0; i < Members.length; i++) {
for (int j = 0; j < Members.length; j++) {
writer.print(Members[i][j] + ",");
}
writer.println();
}
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
} catch(Exception ex){
System.out.println("Could not close writer"+ ex.getMessage());
} finally {
if (writer != null) {
try{
writer.close();
} catch(IOException ex) {
System.out.print("Error while closing file: "+ ex.getMessage())
}
}
}
It seems like what you actually want is this:
...
finally {
if (writer!=null) {
try {
writer.close();
} catch (Exception e) {
System.out.println("Could not close writer");
}
}
}
That is, have a dedicated try/catch around your writer.close() call to report that an error was thrown by closing the writer.
Also, you need to initialise the writer to null. You can't do if (writer!=null) (or indeed anything else with writer) if the writer might never have been assigned.
So change your writer declaration to:
PrintWriter writer = null;
how wold i take the avg of the fallowing program and save the out come to a text file to be printed out
import java.util.Scanner;
public class freethrowpercent {
public static void main(String[] args) {
double freethrowsmade = 1;
double freethrowsmissed = 0;
Scanner input = new Scanner(System.in);
System.out.println("enter 1 if freethorw is made enter 0 for freethrows missed");
freethrowsmade = input.nextDouble() + 1;
freethrowsmissed = input.nextDouble() + 0;
double answer = freethrowsmade / 2 * 100;
System.out.println("percent is" + answer);
}
if that is possable
First, I suggest getting familiar with basic I/O in Java.
If your intention was to write answer to a file, here's one way to do it:
FileWriter writer = null;
try {
String str = Double.toString(answer);
File f = new File("/path/to/file.txt");
writer = new FileWriter(f);
writer.write(str);
} catch (IOException ex) {
} finally {
try {
writer.close();
} catch (IOException ex) {
}
}
}
I cant figure out how to loop through this instead of just repeating the code, bugging the hell outta me! FYI assignment has already been turned in using 5 iterations of code, just wanted to learn how to implement the string array holding file contents into a for loop for future knowledge. I have tried for a few hours but it just prints the filename, cant seem to get the file contents.
/*************************************************************************
* LinuxSys.java
*
* This program reads text from a file
**************************************************************************/
import java.util.*;
import java.io.*;
public class LinuxSys {
public static void main (String[] args) {
String systemInfo[] = new String [5];
int i = 0;
// using _ to simulate file paths to test on local cpu, as it is easier/quicker
// than logging onto server/copy pasting code into new pico file
systemInfo[0] = "_proc_sys_kernel_hostname.txt"; //local files
systemInfo[1] = "_proc_meminfo.txt"; //local files
systemInfo[2] = "_proc_version.txt"; //local files
systemInfo[3] = "_proc_sys_kernel_hostname.txt"; //local files
//systemInfo[0] = "_proc_sys_kernel_hostname.txt"; //local files
// 1st try to print server host name file
try {
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++; // increment systemInfo[] array position
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
// 2nd try to print server memory file
{
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++; // increment systemInfo[] array position
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
// 3rd try to print version file
try {
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++;
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
} // end main
} // end class
for(int i=0; i < systemInfo.size; ++i)
{
// the code you want to repeat with i varying each time
}
or
int i=0;
while(i < systemInfo.size)
{
// the code you want to repeat with i varying each time
++i;
}
or
int i=0;
while(i++ < systemInfo.size)
{
// the code you want to repeat with i varying each time
}
or
int i=0;
do
{
// the code you want to repeat with i varying each time
}
while(++i < systemInfo.size)
or...