I am try to get what it printed from text.txt, make a new file that is text2.txt and put the print results in that file. All I know how to do is read and use the first one.
try{
sc = new Scanner(new File(filename));
}
catch (Exception e){
System.exit(1);
}
Mena is right, you should use chaining of classes from within the java.io package. You'll have to adjust text.txt and text2.txt in order to fit into your application, but this should get the job done:
import java.io.*;
public class Copier{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(new File("text.txt")));
File outputFile = new File("text2.txt");
outputFile.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
String line = null;
while(true){
line = br.readLine();
if(line == null)
break;
bw.write(line);
bw.newLine();
}
br.close();
bw.close();
}
}
Related
What i'm trying to do, is to replace a symbol in a file text which contains over 4000 lines but using the below code, after the program ends, it only remain 500 lines. Why is this file truncated? How to solve this?
This is my code:
ArrayList<String> arrayList = new ArrayList<>();
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {System.err.println(e);}
}
} catch (Exception e) {e.printStackTrace();}
Thanks in advance!
new BufferedWriter(new FileWriter(file)) clear file.
You should open it only once. Also you reading and writing to the same file. You should use different files.
Like this
try (FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
bw.write(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
You are writing to the same file while you are reading it. This won't work. Once you start writing, the file becomes empty (plus whatever you've written), so subsequent reads will report end-of-file. Your ~500 lines will be buffered input from the first read.
One solution is to do all the reading first, before opening the file again for writing:
Array<String> arrayList = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
while ((String line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {
System.err.println(e);
}
Here, first the program slurps the file into a List<String>, fixing the lines as it goes. Then it writes all the lines back out to the file.
There are circumstances in which this model is appropriate. For example, you might be building a non-linear data structure from the file content. Or you might need to see the last line before you can modify earlier lines (and be unable to re-open the data source from the start).
However I'd suggest a method that's more thrifty with memory. You don't need to keep all those lines in memory. You can read one line, fix it up, then forget about it. But to do this, you'll need to write to a second file.
String filein = "inputfile";
String fileout = filein + ".tmp";
try(
BufferedReader reader = new BufferedReader(new FileReader(filein));
Writer writer = new BufferedWriter(FileWriter(fileout))
) {
while ((String line = bufferedReader.readLine()) != null) {
writer.write(line.replace("þ", "t");
}
}
Files.move(Paths.get(fileout)),
Paths.get(filein),
CopyOption.REPLACE_EXISTING);
I have left out the necessary exception catching -- add back in as required.
I'm doing a program that needs to take a text file (test.txt) and make a copy of it and print it out. So far I am only able to print out the original file. I have searched for a way of doing this but there doesn't seem to be any help that I can understand, I am very new to java. I am at least looking for guidance, not just the full answer.
my code so far...
import java.io.*;
public class Copy{
public static void main(String [] args){
try{
FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
File a = new File("test.txt");
FileReader fr = new FileReader(a);
File b = new File("Copied.txt");
FileWriter fw = new FileWriter(b);
while(true){
String line = br.readLine();
if(line != null){
System.out.println(line);
} else{
br.close();
break;
}
}
} catch(FileNotFoundException e){
System.out.println("Error: " + e.getMessage());
} catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
}
}
Again any bit of help will be greatly appreciated since I am trying to learn this. Thank you
Normally, I'd recommend using Files.copy just for it's simplicty, but since you need to "print" the content at the same time, we can make use of your code.
First, however, as a general rule of thumb, if you open it, you should close it. This makes sure that you're not leaving resources open which might affect other parts of your code.
See The try-with-resources Statement for more details.
Next, once you've read a line of text from the source file, you actually need to write it to the destination file, for example...
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("Copied.txt"))) {
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
bw.write(text);
bw.newLine();
}
}
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
You can use Files.copy() if you are using Java 1.7 or higher
File src = "your File";
File dest = "your copy target"
Files.copy(src.toPath(),dest.toPath());
Link to Javadoc
Change your FileWriter into a PrintStream:
PrintStream fw = new PrintStream(b);
Then you should be able to write to that file using:
fw.println(line);
I want to export the character's name and gender to a text file. Also, I need to export on both Mac and PC computers. I've tried various methods, but none has worked for me or I might have placed them incorrectly.
I changed my code with my attempt:
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
public class Character {
public static void main (String[] args) {
String characterGender;
String characterName;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Ricardo's character creator!");
System.out.println("Is your character a boy or a girl?");
characterGender = scan.nextLine();
if (characterGender.equals("girl")) {
System.out.println("Awesome! Please enter her name: ");
characterName = scan.nextLine();
} else {
System.out.println("Awesome! Please enter his name: ");
characterName = scan.nextLine();
}
System.out.print("Alright! " + characterName + " has been created!");
PrintWriter out = new PrintWriter("Character.txt");
out.println(characterName);
out.println(characterGender);
out.close();
}
}
I'm getting an error like this:
Character.java:34: error: unreported exception FileNotFoundException; must be caught or declared to be thrown.
You need to handle the FileNotFoundException. This can be done either by:
Catching the exception (Preferred method):
PrintWriter out;
try {
out = new PrintWriter("Character.txt");
out.println(characterName);
out.println(characterGender);
out.close();
} catch (FileNotFoundException e) {
System.err.println("File doesn't exist");
e.printStackTrace();
}
or by throwing the exception:
public static void main (String[] args) throws FileNotFoundException
Note: import java.io.FileNotFoundException; must be included in both cases.
Here is some java documentation on Exceptions.
Try using File writer Instead of print Writer.
Below is my example code, Hope you do not mind the hard interpretation.
String filetowrite = "C:/Users/Desktop/test.txt"; // Point to your location
FileWriter fw = new FileWriter(filetowrite);
fw.write("Hello, This is the test");
fw.close();
Since you are reading data from Console & writing it to file it is recommended to use BufferedReader & BufferedWriter for it. To handle exception & if you want to add details of exception occurred in Log file using Log4j, you can do something like below :
BufferedReader br = null;
BufferedWriter bw = null
Logger logger = LogManager.getLogger(Character.class);
try {
String data;
br = new BufferedReader(new InputStreamReader(System.in));
File file = new File("Character.txt");
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
while ((data = br.readLine()) != null) {
System.out.println(data);
bw.write(data);
}
} catch (IOException e) {
StringWriter() stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.fatal(stack.toString(), Character.class);
} finally {
try {
if (br != null && bw != null){
bw.close();
br.close();
}
} catch (IOException ex) {
StringWriter() stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.fatal(stack.toString(), Character.class);
}
}
OR
You can use try-with-resources, available from JDK 1.7 onwards, which will take care of closing resources used. In your case, it's a file.
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
String data;
File file = new File("Character.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while ((data = br.readLine()) != null) {
System.out.println(data);
bw.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
I have method which writes some data to file. I use PrintWriter, BufferedWriter and FileWriter as shown below
public void writeToFile(String FileName){
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(FileName)));
for(Cars car : list){
pw.println(car.getType());
pw.println(car.getMaxSpeed());
pw.println(car.getOwner());
pw.println();
pw.flush();
}
pw.close();
}
catch(IOException ex){
System.err.println(ex);
}
}
Now how can I read this data from file? I tried to use InputStreamReader, BufferedReader and FileInputStream, but my NetBeans shows me an error message
public void readFromFile() throws IOException {
InputStreamReader fr = null;
try {
fr = new InputStreamReader(new BufferedReader(new FileInputStream(new FileReader("c:\\cars.txt"))));
System.out.println(fr.read());
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
fr.close();
}
}
What is wrong with this method?
BufferedReader in = new BufferedReader(new FileReader("file.in"));
BufferedWriter out = new BufferedWriter(new FileWriter("file.out"));
String line = in.readLine(); // <-- read whole line
StringTokenizer tk = new StringTokenizer(line);
int a = Integer.parseInt(tk.nextToken()); // <-- read single word on line and parse to int
out.write(""+a);
out.flush();
There are several problems in your code :
1) An InputStreamReader takes an InputStream as an argument not a Reader. See http://docs.oracle.com/javase/6/docs/api/java/io/InputStreamReader.html.
2) The FileInputStream does not accept a Reader as argument as well (it takes a File, a FileDescriptor, or a String). See : http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html
3) A BufferedReader reads the File line by line normally. The read() method only reads a single character.
A possible solution could be :
fr = new BufferedReader(new InputStreamReader(new FileInputStream(new File("c:\\cars.txt"))));
String line = "";
while((line = fr.readLine()) != null) {
System.out.println(line);
}
Btw : It would be easier for others to help you, if you provide the exact error-message or even better the StackTrace.
Simple error: Cannot resolve constructor 'FileInputStream(java.io.FileReader)', required constructor not exist in API.
Your original code was:
new PrintWriter(new BufferedWriter(new FileWriter(FileName)));
so for reading, you need
new PrintReader(new BufferedReader(new FileReader(FileName)));
but PrintReader is not needed (not exist), so all you need is:
new BufferedReader(new FileReader(FileName))
PrinterWriter prints formatted representations of objects to a text-output stream, but when reading text is always formatted, so PrinterReader not exist.
You are writing line by line, so also read line by line :) Example:
public void readFromFile() throws IOException {
BufferedReader bufferedReader = null;
try {
String sCurrentLine;
bufferedReader = new BufferedReader(new FileReader("c:\\cars.txt"));
while ((sCurrentLine = bufferedReader.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
bufferedReader.close();
}
}
or better (JDK7)
void readFromFile() throws IOException {
Path path = Paths.get("c:\\cars.txt");
try (BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset())){
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
I want to replace the second line file content, can somebody help please based on the below file format and listener method.
1324254875443
1313131
Paid
0.0
2nd line is long and want to replace to currentTimeMillis().
/************** Pay Button Listener **************/
public class payListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
ArrayList<String> lines = new ArrayList<String>();
String line = null;
try {
FileReader fr = new FileReader("Ticket/" + ticketIDNumber + ".dat");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("Ticket/" + ticketIDNumber + ".dat");
BufferedWriter bw = new BufferedWriter(fw);
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line.replace(System.currentTimeMillis();
lines.add(line);
bw.write(line);
} //end if
} //end try
catch (Exception e) {
} //end catch
} //end while
}//end method
Although this question is very old I'd like to add that this can be achieved much easier since Java 1.7 with java.nio.file.Files:
List<String> newLines = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8)) {
if (line.contains("1313131")) {
newLines.add(line.replace("1313131", ""+System.currentTimeMillis()));
} else {
newLines.add(line);
}
}
Files.write(Paths.get(fileName), newLines, StandardCharsets.UTF_8);
As proposed in the accepted answer to a similar question:
open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.
Based on your implementation, something similar to:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "try.dat";
String tmpFileName = "tmp_try.dat";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line = line.replace("1313131", ""+System.currentTimeMillis());
bw.write(line+"\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
I could suggest to use Apache Commons IO library. There you'll find the class org.apache.commons.io.FileUtils. You can use it:
File file = new File("... your file...");
List<String> lines = FileUtils.readLines(file);
lines.set(1, ""+System.currentTimeMillis());
FileUtils.writeLines(file, lines);
This code reads entire file contents into a List of Strings and changes the second line's content, then writes the list back to the file.
I'm not sure reading and writing the same file simultaneously is a good idea. I think it would be better to read the file line by line into a String array, replace the second line and then write the String array back into the file.