I need to read from one text file(carsAndBikes.txt) and the write in either cars.txt or bikes.txt
carsAndBikes contains a list of cars and bikes and the first character of each name is C or B (C for Car and B for Bike). So far i have that but its showing cars and bikes content. Instead of the separated content.(CARS ONLY OR BIKES ONLY)
public static void separateCarsAndBikes(String filename) throws FileNotFoundException, IOException
{
//complete the body of this method to create two text files
//cars.txt will contain only cars
//bikes.txt will contain only bikes
File fr = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
Scanner scanFile = new Scanner(fr);
String line;
while(scanFile.hasNextLine())
{
line = scanFile.nextLine();
if(line.startsWith("C"))
{
try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\cars.txt"))
{
printWriter.write(line);
}
catch(Exception e)
{
System.out.println("Message" + e);
}
}
else
{
try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\bikes.txt"))
{
printWriter.write(line);
}
catch(Exception e)
{
System.out.println("Message" + e);
}
}
}
//close the file
scanFile.close();
}
You're checking if the input filename starts with a c instead of checking if the line read starts with a c.
You should also open both your output files before your loop, and close them both after the loop.
// Open input file for reading
File file = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
BufferedReader br = new BufferedReader(new FileReader(file)));
// Open bike outputfile for writing
// Open cars outputfile for writing
// loop over input file contents
String line;
while( line = br.readLine()) != null ) {
// check the start of line for the character
if (line.startsWith("C") {
// write to cars
} else {
// write to bikes
}
}
// close all files
Related
I have tried to implement a simple program to delete a particular text from a file, some how it is not able to delete it. I am reading entire file content into a temp file , delete the user input string from it and update the content to the original file.
Any help would be highly appreciated.
public class TextEraser{
public static void main(String[] args) throws IOException {
System.out.print("Enter a string to remove : ");
Scanner scanner = new Scanner(System. in);
String inputString = scanner. nextLine();
// Locate the file
File file = new File("/Users/lobsang/documents/input.txt");
//create temporary file
File temp = File.createTempFile("file", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
// Create a buffered reader
// to read each line from a file.
BufferedReader in = new BufferedReader(new FileReader(file));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
String s = in.readLine();
// Read each line from the file and echo it to the screen.
while (s !=null) {
s=s.replace(inputString,"");
s = in.readLine();
}
writer.println(s);
// Close the buffered reader
in.close();
writer.close();
file.delete();
temp.renameTo(file);
} catch (FileNotFoundException e1) {
// If this file does not exist
System.err.println("File not found: " + file);
}
}
After replace with input string, write string immediate in file.
while (s != null) {
s = s.replace(inputString, "");
writer.write(s);
// writer.newLine();
s = in.readLine();
}
For new line , use BufferedWriter in place of PrintWriter, it contains method newLine()
writer.newLine();
Remove this
writer.println(s);
So I'm having a few troubles here. I need to be able to write my output to a file, and have it contain only the keywords specified in the code. This code is writing nothing to the file, and it only opens another box for user input. How do I get it to close the input box after the user inputs the file name, get it to write the output to the file, and get the output to display in the compiler? Thanks!
import java.util.*;
import java.io.*;
public class Classname {
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException,
FileNotFoundException {
String filename;
// Connecting to a file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the text file to a file object
File log = new File( filename);
String textLine = null; // Null
String outLine = ""; // Null
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
try
{
// assigns the file to a filereader object..this will throw an error if
the file does not exist or cannot be found
BufferedReader infile = new BufferedReader(new FileReader(log));
try
{
// read data from a file..this will throw and error if something goes
wrong reading (empty or past end of file)
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.printf("%s\n",outLine);
}// end of while
} // end of try
finally // finally blocks get executed even if an exception is thrown
{
infile.close();
outFile.close();
}
}// end of try
catch (FileNotFoundException nf) // this goes with the first try because it
will throw a FileNotFound exception
{
System.out.println("The file \""+log+"\" was not found");
}
catch (IOException ioex) // this goes with the second try because it will
throw an IOexception
{
System.out.println("Error reading the file");
}
} /// end of main
} // end of class
What you need is to end the while(sc.hasNext()) while loop because the Scanner sc will always have a next because you are literally saying asking yourself if you got the line from the user then wait for next line with sc.nextLine(); then you are putting it into a string so next time you ask yourself do i have the line the answer is yes,anyways it's a little complicated to get over this issue you need to change the while loop to have a special word that will brake it,so you have to change it from:
while(sc.hasNext()){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
To,for example:
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
}
Also you need to check if the file entered by the user exists and actually add the text from the console to the file,so it would look something like this:
if(!log.exists())log.createNewFile();
// Connecting to a file with a buffer
PrintWriter logFile = new PrintWriter(
new BufferedWriter(
new FileWriter(log.getAbsolutePath())));
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
logFile.println(line);
}
logFile.close();
Now all we have to do is print the output to the console when writing it to the logFile,so the while((textLine = infile.readLine()) != null),will now look a little something like this:
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.println(outLine);
System.out.println(outLine);
}// end of while
} // end of try
So in the end the hole thing should look a little something like this:
import java.util.*;
import java.io.*;
public class Classname{
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException,
FileNotFoundException {
String filename;
// Connecting to a file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the text file to a file object
File log = new File(filename);
String textLine = null; // Null
String outLine = ""; // Null
if(!log.exists())log.createNewFile();
// Connecting to a file with a buffer
PrintWriter logFile = new PrintWriter(
new BufferedWriter(
new FileWriter(log.getAbsolutePath())));
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
logFile.println(line);
}
logFile.close();
try{
// assigns the file to a filereader object..this will throw an error if the file does not exist or cannot be found
BufferedReader infile = new BufferedReader(new FileReader(log));
try
{
// read data from a file..this will throw and error if something goes wrong reading (empty or past end of file)
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.println(outLine);
System.out.println(outLine);
}// end of while
} // end of try
finally // finally blocks get executed even if an exception is thrown
{
infile.close();
outFile.close();
}
}// end of try
catch (FileNotFoundException nf) // this goes with the first try because it will throw a FileNotFound exception
{
System.out.println("The file \""+log+"\" was not found");
}
catch (IOException ioex) // this goes with the second try because it will throw an IOexception
{
System.out.println("Error reading the file");
}
} /// end of main
} // end of class
If this is not what you are looking for i'm sorry,but i tried to make it do want you described you wanted,i mean it does write the output to the file, and get the output to display in the compiler,here's what the compiler console looks like:
Please enter full name of the file: test.txt
hi
hi
hi
END
HI
HI
HI
I'm sorry if this is not what you wanted but i tried my best,hope it helps.
I am trying to replace a string from a js file which have content like this
........
minimumSupportedVersion: '1.1.0',
........
now 'm trying to replace the 1.1.0 with 1.1.1. My code is searching the text but not replacing. Can anyone help me with this. Thanks in advance.
public class replacestring {
public static void main(String[] args)throws Exception
{
try{
FileReader fr = new FileReader("G:/backup/default0/default.js");
BufferedReader br = new BufferedReader(fr);
String line;
while((line=br.readLine()) != null) {
if(line.contains("1.1.0"))
{
System.out.println("searched");
line.replace("1.1.0","1.1.1");
System.out.println("String replaced");
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
First, make sure you are assigning the result of the replace to something, otherwise it's lost, remember, String is immutable, it can't be changed...
line = line.replace("1.1.0","1.1.1");
Second, you will need to write the changes back to some file. I'd recommend that you create a temporary file, to which you can write each `line and when finished, delete the original file and rename the temporary file back into its place
Something like...
File original = new File("G:/backup/default0/default.js");
File tmp = new File("G:/backup/default0/tmpdefault.js");
boolean replace = false;
try (FileReader fr = new FileReader(original);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(tmp);
BufferedWriter bw = new BufferedWriter(fw)) {
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains("1.1.0")) {
System.out.println("searched");
line = line.replace("1.1.0", "1.1.1");
bw.write(line);
bw.newLine();
System.out.println("String replaced");
}
}
replace = true;
} catch (Exception e) {
e.printStackTrace();
}
// Doing this here because I want the files to be closed!
if (replace) {
if (original.delete()) {
if (tmp.renameTo(original)) {
System.out.println("File was updated successfully");
} else {
System.err.println("Failed to rename " + tmp + " to " + original);
}
} else {
System.err.println("Failed to delete " + original);
}
}
for example.
You may also like to take a look at The try-with-resources Statement and make sure you are managing your resources properly
If you're working with Java 7 or above, use the new File I/O API (aka NIO) as
// Get the file path
Path jsFile = Paths.get("C:\\Users\\UserName\\Desktop\\file.js");
// Read all the contents
byte[] content = Files.readAllBytes(jsFile);
// Create a buffer
StringBuilder buffer = new StringBuilder(
new String(content, StandardCharsets.UTF_8)
);
// Search for version code
int pos = buffer.indexOf("1.1.0");
if (pos != -1) {
// Replace if found
buffer.replace(pos, pos + 5, "1.1.1");
// Overwrite with new contents
Files.write(jsFile,
buffer.toString().getBytes(StandardCharsets.UTF_8),
StandardOpenOption.TRUNCATE_EXISTING);
}
I'm assuming your script file size doesn't cross into MBs; use buffered I/O classes otherwise.
I have two files say
abc
cdg
sfh
drt
fgh
and another file
ahj
yuo
jkl
uio
abc
cdg
I want to compare these two files and get output file as
abc
cdg
sfh
drt
fgh
ahj
yuo
jkl
uio
this is my code
public static void MergeFiles(final File priviousModifiedFilesList, final File currentModifiedFilesList,
final File ModifiedFilesList) {
FileWriter fstream = null;
out = null;
try {
fstream = new FileWriter(ModifiedFilesList, true);
out = new BufferedWriter(fstream);
}
catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("merging: " + priviousModifiedFilesList + "\n");
System.out.println("merging: " + currentModifiedFilesList);
FileInputStream fis1;
FileInputStream fis2;
try {
fis1 = new FileInputStream(priviousModifiedFilesList);
BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(fis1));
fis2 = new FileInputStream(currentModifiedFilesList);
BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(fis2));
String Line1;
String Line2;
while (((Line1 = bufferedReader1.readLine()) != null)) {
while ((Line2 = bufferedReader2.readLine()) != null) {
if (Line1.equals(Line2)) {
out.write(Line1);
}
out.write(Line2);
out.newLine();
}
out.write(Line1);
}
bufferedReader1.close();
bufferedReader2.close();
}
catch (IOException e) {
e.printStackTrace();
}
out.close();
}
it writes all the lines from first file and when the lines match it stops.
It's easy:
Read you first file line by line (you can use a Scanner for that).
For each line, write it to the output file (you can use a PrintWriter for that).
Also store the line in a HashSet.
Read your second file line by line.
For each line, check if the line is in the HashSet.
If it's not, write it to the output file.
Close your files.
I am writing a program in Java that writes several lines of information into a CSV file. I want to delete the last line of CSV file, as it is not needed. How would I do this, as the CSV file is created by a PrintWriter, and I don't believe the append method could do this.
The extra line is written because the loop continues for one extra line. This portion of the code is as follows:
public static void obtainInformation() throws IOException {
PrintWriter docketFile = new PrintWriter(new FileWriter("ForclosureCourtDockets"+startingMonth+"_"+startingDay+"_"+startingYear+"-"+endingMonth+"_"+endingDay+"_"+endingYear+".csv", true));
pageContentString = pageContentString.replace('"','*');
int i = 0;
boolean nextDocket = true;
while(nextDocket) {
nextDocket = false;
String propertyCity = "PropertyCity_"+i+"*>";
Pattern propertyCityPattern = Pattern.compile("(?<="+Pattern.quote(propertyCity)+").*?(?=</span>)");
Matcher propertyCityMatcher = propertyCityPattern.matcher(pageContentString);
while (propertyCityMatcher.find()) {
docketFile.write(i+propertyCityMatcher.group().toString()+", ");
nextDocket = true;
}
String descriptionValue = "Description_"+i+"*>";
Pattern descriptionPattern = Pattern.compile("(?<="+Pattern.quote(descriptionValue)+").*?(?=</span>)");
Matcher descriptionMatcher = descriptionPattern.matcher(pageContentString);
while (descriptionMatcher.find()) {
docketFile.write(descriptionMatcher.group().toString()+"\n");
}
i++;
}
docketFile.close();
}
public static void removeLineFromFile() {
try {
File inFile = new File("ForclosureCourtDockets"+startingMonth+"_"+startingDay+"_"+startingYear+"-"+endingMonth+"_"+endingDay+"_"+endingYear+".csv");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader("ForclosureCourtDockets"+startingMonth+"_"+startingDay+"_"+startingYear+"-"+endingMonth+"_"+endingDay+"_"+endingYear+".csv"));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals("^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^")) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
Well, as PrintWriter is just a Writer, which can only append/write/print
So, you can't override the line which you just have written.
Several options you have :
Modify your logic to make sure you don't write the line you want to remove eventually (I think the most logical option)
After writing to file you can use another Reader(say, BufferedReader) to read it again, and then re-write it, without the line you'd like to exclude.
use RandomAccessFile and its seek method to go back and rewrite / remove the line you need.
You could do the following (this is a way to implement kiruwka's first suggestion):
1) write the first line outside of the while loop.
2) Then for each line written within the while loop first output the newline, and only subsequently output the csv line.
This way you will have duplicated code, but you won't end up with a newline at the end of the file. You can also factor out the duplicate code into a helper method.