I some code that takes a file called wonder1.txt and writes the date in that file to another file. Lets say I have more files like wonder2.txt, wonder3.txt, wonder4.txt. How do I write the rest in the same file.
import java.io.*;
import java.util.*;
import java.lang.*;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "/Users/DAndre/Desktop/Alice/new1.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you have list of files, then you can loop over them one by one. Your current code moves inside the loop.
The easier way would be to put all the files in one folder and read from it.
Something like this :
File folder = new File("/Users/DAndre/Desktop/Alice");
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
Related
I need to replace multiple words in txt file using java. This program only replacing the only one word, in whole file.
import java.io.*;
public class MultiReplace
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replaceAll("india", "freedom");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Try this:
import java.io.*;
public class MultiReplace
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
// Replace in the line and append
line = line.replaceAll("india", "freedom");
oldtext += line + "\r\n";
}
reader.close();
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);
writer.flush();
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Refer this to understand why your version is not working.
Your solution is correct!! I ran your program as is and it is able to replace all the india with freedom in the text file
I am trying to read values from CSV file which is present in package com.example.
But when i run code with the following syntax:
DataModel model = new FileDataModel(new File("Dataset.csv"));
It says:
java.io.FileNotFoundException:Dataset.csv
I have also tried using:
DataModel model = new FileDataModel(new File("/com/example/Dataset.csv"));
Still not working.
Any help would be helpful.
Thanks.
If this is the FileDataModel from org.apache.mahout.cf.taste.impl.model.file then it can't take an input stream and needs just a file. The problem is you can't assume the file is available to you that easily (see answer to this question).
It might be better to read the contents of the file and save it to a temp file, then pass that temp file to FileDataModel.
InputStream initStream = getClass().getClasLoader().getResourceAsStream("Dataset.csv");
//simplistic approach is to put all the contents of the file stream into memory at once
// but it would be smarter to buffer and do it in chunks
byte[] buffer = new byte[initStream.available()];
initStream.read(buffer);
//now save the file contents in memory to a temporary file on the disk
//choose your own temporary location - this one is typical for linux
String tempFilePath = "/tmp/Dataset.csv";
File tempFile = new File(tempFilePath);
OutputStream outStream = new FileOutputStream(tempFile);
outStream.write(buffer);
DataModel model = new FileDataModel(new File(tempFilePath));
...
public class ReadCVS {
public static void main(String[] args) {
ReadCVS obj = new ReadCVS();
obj.run();
}
public void run() {
String csvFile = "file path of csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// Do stuff here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
CSV file which is present in package com.example
You can use getResource() or getResourceAsStream() to access the resource from within the package. For example
InputStream is = getClass().getResourceAsStream("/com/example/Dataset.csv");//uses absolute (package root) path
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//read from BufferedReader
(note exception handling and file closing are omitted above for brevity)
I have a program that is suppose to read all the files in my folder and combine the files into on file and place them into a new folder. Some of the files are not being pulled in and I do not know why.
The file names are wonder1.txt, wonder2.txt, wonder3.txt, and wonder4.txt and the folder name is Alice, but only a few of the files are actually in the new folder.
import java.io.*;
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.io.PrintWriter;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
File folder = new File("/Users/DAndre/Desktop/Alice");
//Reads in all the files in that folder
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "/Users/DAndre/Desktop/final/final_copy.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem with your solution is that you haven't initialize PrintWriter in append mode, because of which the new file gets overwritten with the content of the last file that was written.
public static void newFile(String fileContent) {
try {
String newFileLocation = "C:\\Users\\Shayan\\Desktop\\files2\\final_copy.txt";
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(newFileLocation), true /* append = true */));
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
The last argument in the constructor of FileOututStream is set to true, indicating that it should be opened in append mode.
You need to change
PrintWriter writer = new PrintWriter(newFileLocation);
to
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(newFileLocation, true)))
Little explanation: append meant to write it additively, on the contrary write overrides the existing file. In your code you are creating a new file including one of your wonders, but on next iteration the file is recreated. So the content of previous wonder is gone.
With the change PrintWriter object is not recreating the file, instead it writes content to a BufferedWriter which also transfers the stream to an append able FileWriter object.
Little suggest: do not create a PrintWriter object on each iteration.
Second little suggest: You don't need PrintWriter. BufferedWriter itself is good enough as far as I see.
In my below code I wanted to replace the text "DEMO" with "Demographics" but instead of replacing the text it deletes the entire content of the text file.
Contents inside the file:
DEMO
data
morning
PS: I'm a beginner in java
package com.replace.main;
import java.io.*;
public class FileEdit {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String readLine, replacedData;
try {
bw = new BufferedWriter(
new FileWriter(
"Demg.ctl"));
br = new BufferedReader(
new FileReader(
"Demg.ctl"));
System.out.println(br.readLine()); //I Get Null Printed Here
while ((readLine = br.readLine())!= null) {
System.out.println("Inside While Loop");
System.out.println(readLine);
if (readLine.equals("DEMO")) {
System.out.println("Inside if loop");
replacedData = readLine.replaceAll("DEMO","Demographics");
}
}
System.out.println("After While");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You open a Writer to your file, but you don't write anything. This means that your file is replaced with an empty file.
Besides this you also need to close your writer, not just the reader.
And last but not least, your if condition is wrong.
if (readLine.equals("DEMO")) {
should read
if (readLine.contains("DEMO")) {
Otherwise it would only return true if your line contained "DEMO" but nothing else.
I'm updating the answer to my own question.
package com.replace.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileEdit
{
public static void main(String args[])
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Demg.ctl"));
String readLine = "";
String oldtext = "";
while((readLine = reader.readLine()) != null)
{
oldtext += readLine + "\r\n";
}
reader.close();
// To replace the text
String newtext = oldtext.replaceAll("DEMO", "Demographics");
FileWriter writer = new FileWriter("Demg.ctl");
writer.write(newtext);
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I can't figure out for the life of me what is wrong with this program:
import java.io.*;
public class EncyptionAssignment
{
public static void main (String[] args) throws IOException
{
String line;
BufferedReader in;
in = new BufferedReader(new FileReader("notepad encypt.me.txt"));
line = in.readLine();
while(line != null)
{
System.out.println(line);
line = in.readLine();
}
System.out.println(line);
}
}
The error message says that the file can't be found, but I know that the file already exists. Do I need to save the file in a special folder?
The error is "notepad encypt.me.txt".
Since your file is named "encypt.me.txt", you can't put a "notepad" in front of its name. Moreover, the file named "notepad encypt.me.txt" probably didn't exist or is not the one that you want to open.
Additionally, you have to provide the path ( absolute or relative ) of your file if it's not located in your project folder.
I will take the hypothesis that your are on a Microsoft Windows system.
If your file has as absolute path of "C:\foo\bar\encypt.me.txt", you will have to pass it as "C:\\foo\\bar\\encypt.me.txt" or as "C:"+File.separatorChar+"foo"+File.separatorChar+"bar"+File.separatorChar+encypt.me.txt".
If it's still not working, you should verify that the file :
1) Exist at the path provided.
You can do it by using the following piece of code:
File encyptFile=new File("C:\\foo\\bar\\encypt.me.txt");
System.out.println(encyptFile.exists());
If the path provided is the right one, it should be at true.
2) Can be read by the application
You can do it by using the following piece of code:
File encyptFile=new File("C:\\foo\\bar\\encypt.me.txt");
System.out.println(encyptFile.canRead());
If you have the permission to read the file, it should be at true.
More informations:
Javadoc of File
Informations about Path in computing
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
package com.mkyong.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Reference: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/