import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class TextFile {
private static void doReadWriteTextFile() {
try {
// input/output file names
String inputFileName = "README_InputFile.rtf";
// Create FileReader Object
FileReader inputFileReader = new FileReader(inputFileName);
// Create Buffered/PrintWriter Objects
BufferedReader inputStream = new BufferedReader(inputFileReader);
while ((inLine = inputStream.readLine()) != null) {
System.out.println(inLine);
}
inputStream.close();
} catch (IOException e) {
System.out.println("IOException:");
e.printStackTrace();
}
}
public static void main(String[] args) {
doReadTextFile();
}
}
I'm just learning Java, so take it easy on me. My program's objective is to read a text file and output it into another text file in reverse order. The problem is the professor taught us to to deal with strings and reverse it and such, but nothing about importing/exporting files. Instead, he gave us the following sample code which should import a file. The file returns 3 errors: The first two deal with inLine not being a symbol on lines 24 and 25. The last cannot find the symbol doReadTextFile on line 40.
I have no idea how to read this file and make the necessary changes to reverse and output into a new file. Any help is hugely appreciated.
I also had to change the file type from .txt to .rtf. I'm not sure if that affects how I need to go about this.
EDIT I defined inLine and fixed the doReadWritetextFile naming error, which fixed all my compiling errors. Any help on outputting into new file still appreciated!
I'm also aware he gave me bad sample code. It's supposed to be so we can learn troubleshooting, but with no working code to go off of and very extremely knowledge of the language, it's very difficult to see what's wrong. Thanks for the help!
The good practice will be to use a BufferedFileReader
BufferedFileReader bf = new BufferedFileReader(new FileReader(new File("your_file.your_extention")));
Then you can read lines in your file :
// Initilisation of the inLine variable...
String inLine = null;
while((inLine = bf.readLine()) != null){
System.out.println(inLine);
}
To output a file, you can use StringBuilder to hold the file contents:
private static void doReadWriteTextFile()
{
....
StringBuilder sb = new StringBuilder();
while ((inLine = inputStream.readLine()) != null)
{
sb.append(inline);
}
FileWriter writer = new FileWriter(new File("C:\\temp\\test.txt"));
BufferedWriter bw = new BufferedWriter(writer);
w.write(sb.toString());
bw.close();
}
Related
I have a .csv file with different countries weather data in which I have to split data into different csv where country = India one .csv should be created with name row.csv if country other than India it should create as output.csv Please help since Iam a beginner unable to resolve even afgter several attempts.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class weather {
public static void main(String[] args) {
try
{
String Country =null;
String India = null;
String s;
FileReader fr = new FileReader("C:\\Users\\pratap\\Downloads\\weather1.csv");
BufferedReader br = new BufferedReader(fr);
if (Country != India)
{
FileWriter fw = new FileWriter("C:\\Users\\pratap\\Downloads\\output.csv" , true);
while ((s = br.readLine()) != null)
{
fw.write(s);
fw.flush();
}
br.close();
fw.close();
System.out.println("file copied");
}
else
{
FileWriter fw = new FileWriter("C:\\Users\\pratap\\Downloads\\row.csv" , true);
while((s = br.readLine()) != null)
{
fw.write(s);
fw.flush();
}
br.close();
fw.close();
System.out.println("file copied");
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Okay, you don't seem to be even close. I'm not going to write this for you, as it sounds like a homework assignment, but I'm going to nudge you.
It sounds like you have one big file, and you're trying to pull out only the data for a single country, something you might be able to do with:
grep "India" < input.csv > output.csv
Clearly, that's probably an insufficent regular expression, but it sounds like that's what you're trying to code.
What you're going to need to do as a basic approach:
Open the input and output files
Loop, reading one line at a time.
For each line, determine, "Is this line for India?"
If so, write to the output file
Close both files and you're done.
As I don't know the structure of your data, I don't know exactly how you'll determine if a particular line is for India. That may complicate that particular step, but maybe not.
But for that step, I'd write a method:
bool isForIndia(const std::string & inputLine)
You'll have to extract out the country portion, Parsing CSV files can be a pain in the butt, though, so this is the hardest part of the entire problem.
Most of this is easy, however, if you follow the structure outlined.
Basically I am trying to take information from a text file and turn it into a string. The code I have is:
FileInputStream inputStream = new FileInputStream("filename.txt");
try
{
String everything = IOUtils.toString(inputStream);
}
finally
{
inputStream.close();
}
the error message I get is -->
java:53: cannot find symbol
symbol : class IOUtils
location: class CheckSystem
I assumed this was because of my imports, but I have io and util and even text imported (just as below)
import java.util.*;
import java.text.*;
import java.io.*;
Why can't I access the IOUtils class and its methods? If that cannot be answered, an alternative but very simple means of reading a text file into a string would be fine.
You don't need anything outside of standard JDK to read from a text file easily and efficiently. For example you can do so like this:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} catch(IOException e) {
}
finally {
br.close();
}
taken from: Reading a plain text file in Java
The everything String contains the contents of the file.txt, which must be located in the same directory as where the java class file is being run from.
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
I am trying to generate random numbers as ids, and save them in a file to easily access them. I am currently using BufferedWriter in order to write these to the file, but the problem is that I am not too sure about how to go about finding where I should start writing into the file. I am currently trying to use BufferedReader to figure out where the next line is to write, but I am not sure how I am supposed to save this offset or anything, or how a new line is represented.
void createIds(){
File writeId = new File("peopleIDs.txt");
try {
FileReader fr = new FileReader(writeId);
BufferedReader in = new BufferedReader(fr);
FileWriter fw = new FileWriter(writeId);
BufferedWriter out = new BufferedWriter(fw);
String line;
while((line = in.readLine()) != null){
//How do I save where the last line of null is?
continue;
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
If you simply want to add IDs to the end of the file, use the following FileWriter constructor:
FileWriter fw = new FileWriter(writeId, true);
This opens the FileWriter in append mode, allowing you to write output to a pre-existing file.
If you would like to write the IDs to a particular location within an existing file rather than just to the end, I am not sure if this is possible without first parsing the file's contents.
For more information, see the JavaDoc for FileWriter.
We need more information about the file itself: what are you searching for with BufferedReader?
If the file is empty/newly created then you don't need BufferedReader at all. Just create the PrintWriter and save your numbers.
I'm just guessing here, but I think the real problem is that you're not sure how to generate random numbers (since this doesn't appear in your example code).
Here's some example code that'll write random numbers into a text file:
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Example
{
public static void main(String[] args)
{
Random r;
PrintWriter writer;
r = new Random();
try
{
writer = new PrintWriter(new BufferedWriter(new FileWriter("Examplefile.txt")));
for (int i = 0; i < 10; i++)
writer.println(Integer.toString(r.nextInt(10)));
writer.close();
}
catch (IOException e)
{
}
}
}
You can do
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File("abc.txt"),true)));
writer.append("test");
} catch (IOException e) {
e.printStackTrace();
}
Okay, so I've seen a few questions about this, but the answers were a bit overwhelming and quite varied. Obviously I'm looking for the simplest solution, but a want to be able to read in lines from a text file as strings and store them in an array list. I have an addItem(String item) method for each thing that would be imported to add it to the array list, but I don't know how to import the file correctly and have each line as an individual string.
You're looking for something like BufferedReader, which has functions for reading input from a file line by line.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("inputFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine = br.readLine())!= null) {
addItem(strLine);
}
} catch(Exception e) {
System.out.println(e);
}
}
I'm not at my computer so I didn't compile this answer but I believe you are looking for somehing like this:
// file is your txt file.
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line, i.e, add to your list
}
br.close();
Hope it helps
I wrote the below part of the code but I couldn't bind the arraylist with search and replace
so my csv file is as like below
1/1/1;7/6/1
1/1/2;7/7/1
I want to search the file 1.cfg for 1/1/1 and change it to 7/6/1 and 1/1/2 change to 7/7/1 and it goes so on.
Thank you all in advance
It's now only printing in a new file only the last line of the old File
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ChangeConfiguration {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream degistirilecek = new FileInputStream("c:/Config_Changer.csv");
FileInputStream config = new FileInputStream("c:/1.cfg");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(config);
DataInputStream degistir = new DataInputStream(degistirilecek);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedReader brdegis = new BufferedReader(new InputStreamReader(degistir));
List<Object> arrayLines = new ArrayList<Object>();
Object contents;
while ((contents = brdegis.readLine()) != null)
{
arrayLines.add(contents);
}
System.out.println(arrayLines + "\n");
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//Couldn't modify this part error is here :(
BufferedWriter out = new BufferedWriter(new FileWriter("c:/1_new.cfg"));
out.write(strLine);
out.close();
}
in.close();
degistir.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
You are opening the file for reading when you declare:
BufferedReader br = new BufferedReader(new InputStreamReader(in));
If you know the entire file will fit in memory, I recommend doing the following :
Open the file and read it's contents in memory into a giant string, then close the file.
Apply your replace in one shot to the giant string.
Open the file and write (e.g use a BufferedWriter) out the contents of the giant string, then close the file.
As a side note, your code as posted will not compile. The quality of the responses you receive are correlated with the quality of the question asked. Always include an SCCE with your question to increase the chance of getting a precise answer to your question.
can you elaborate the purpose of the program?
if it is a simple content replacement in a file.
then just read a line and store it in a string. then use string replace method for replacing a text in a string.
eg:
newStrog=oldString.replace(oldVlue,newValue);