csv file (test.csv)
Name|Gender
Ali|M
Abu|M
Ahmad|M
Siti|F
Raju|M
properties file (config.properties)
IncomingFileName = test.csv
OuputFileNameExtension = txt
test1.java
public class test1 {
public static Properties prop1 = new Properties();
public static String nameList;
public test1() throws FileNotFoundException, IOException{
InputStream input1 = new FileInputStream("config.properties");
configProp.load(input1);
}
public static void main(String[] args) throws IOException {
test1 t1 = new test1();
t1.readFileLength(configProp.getProperty("IncomingFileName"));
}
public void readFileLength(String filename){
File file = new File(filename);
try(Scanner scanner = new Scanner(file)){
int j = 1;
while (scanner.hasNextLine()) {
String line = scanner.nextLine() + " ";
if (j != 1) {
String[] records = line.split("\\|");
String name = records[0];
String gender = records[1];
nameList = name;
}
j++;
}
if(j != 0){
writeFile("file."+configProp.getProperty
("OutputFileNameExtension"), nameList);
}
scanner.close();
}catch(IOException x){
}
public void writeFile(String fileName, String nameList) throws IOException{
File file = new File(fileName);
FileWriter fileWriter = new FileWriter(file);
System.out.println(nameList); //show one name only
fileWriter.flush();
fileWriter.close();
}
From the above code, I want to write all the name into the csv file.
However, I just can show 1 name only. (i.e Ali). How do I show all the
name in csv file?
Create a linked list of the names: replace String nameList; with LinkedList<String> names = new LinkedList<>();
add each name to the list : replace nameList = name; with names.add(records[0]);
then add the names to the new file:
public void writeFile(String fileName, List<String> names) throws IOException{
File file = new File(fileName);
FileWriter fileWriter = new FileWriter(file);
for(String name: names){
filewriter.write(name);//writes the current name to the file. you may need to add a /n or a "," to the name to get approprite line seperations and comas
}
fileWriter.flush();
fileWriter.close();
}
How about change:
namelist = name
to
namelist = namelist + " " + name
and only calls the writeFile method one time.
Or you could declare namelist as a StringBuilder, and use the append() method to do the same thing.
Related
I'm currently testing the edit method for the CSV file. However, the File.Delete() and File.Rename() is highlighting in yellow and told me that these commands will be ignored. What is the cause of this and how do I fix it?
public class Main {
private static Scanner x;
public static void main(String[] args) {
String filepath = "Leads.csv";
String editerm = "Lead_000";
String newID = "Lead_003";
String newname = "Cac";
}
public static void editRecord(String filepath, String editerm, String newID, String newname) {
String tempfile = "temp.csv;";
File oldfile = new File(filepath);
File newfile = new File(tempfile);
String ID = "";
String name = "";
try {
FileWriter fw = new FileWriter(tempfile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,\n]");
while (x.hasNext()) {
ID = x.next();
name = x.next();
if (ID.equals(editerm)) {
pw.println(newID + "," + newname);
} else {
pw.println(ID + "," + name);
}
x.close();
pw.flush();
pw.close();
oldfile.delete();
File dump = new File(filepath);
newfile.renameTo(dump);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I guess that IDE marks your File.Delete() and File.Rename() lines.
It says that it will ignore the result of this function because you don't store the return value.
If you want to fix it, you should store the return values
boolean result = oldfile.delete();
I have a test.txt in my active directory.I need to create three methods:
First one has to create an output file and reverse the order of the lines.
Second the order of the words
The third the order of the lines and the words.
test.txt contains the input.
I developed every method to work on its own but somehow when I call all three at the same time it doesnt seem to work.
What am i doing wrong?
This is my main:
import java.io.*;
public class DemoReverser {
public static void main (String [] args)
throws IOException, FileNotFoundException {
Reverser r = new Reverser(new File("test.txt"));
r.completeReverse(new File("out3.txt"));
r.reverseEachLine(new File("out2.txt"));
r.reverseLines(new File("out1.txt"));
} }
and this is my class.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc = null ;
Scanner sc2 = null;
//constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file)throws FileNotFoundException, IOException{
sc = new Scanner (file);
}
//this method reverses the order of the lines in the output
//prints to output file specified in argument.
public void reverseLines(File outpr)throws FileNotFoundException, IOException{
List<String> wordsarraylist = new ArrayList<String>();
while(sc.hasNextLine()){
wordsarraylist.add(sc.nextLine());
}
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str+System.lineSeparator());
}
writer.flush();
writer.close();
}
//this method reverses the order of the words in each line of the input
//and prints it to output file specified in argument.
public void reverseEachLine(File outpr)throws FileNotFoundException, IOException{
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
}
//this methhod reverses the order of the words in each sentence of the input
//then writes it to output file specified in argument
//then uses the output file as input and reverses the order of the sentences
//then overwrites the ouput file with the result
//the output file will contain the input sentences with their words reversed
// and the order of sentences reversed.
public void completeReverse(File outpr) throws FileNotFoundException, IOException{
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist2 = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist2);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist2) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
sc2 = new Scanner (outpr);
List<String> wordsarraylist = new ArrayList<String>();
while(sc2.hasNextLine()){
wordsarraylist.add(sc2.nextLine());
}
Collections.reverse(wordsarraylist);
PrintWriter erase = new PrintWriter(outpr);
erase.print("");
// erase.flush();
erase.close();
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str+System.lineSeparator());
}
writer.flush();
writer.close();
}
}
When I run the program, out1 file gests created, which is the output file for my first method but it is empty. I don't get out2 file created by second method and out3 is fine.
What am I doing wrong? What is missed
Add writer.flush(); before writer.close(); in all three methods
And other thing - Scanner is initialized with File only once in constructor. It has to be re-initialized in other methods.
sc = new Scanner (file); // the scanner should be available in all three methods
For catching exceptions, use
try{
// your code
}catch(Exception err){
err.printStackTrace();
}
After running your code, output3.txt is generated (First method call). Later Scanner is not available since end of the file has been reached.
Fix : Scanner should be re-initialized for next two methods.
EDIT: ( Updating answer with your chat feedback)
1) Create three scanners sc1,sc2 and sc3 due to your limitations. I would suggest to re-initialize the scanner in every method with the file being worked upon.
2) String reversal in easier way without using StringBuffer reverse() API ( For learning purpose)
int length = str.length();
String reverse = "";
for ( int i = length - 1 ; i >= 0 ; i-- ){
reverse = reverse + str.charAt(i);
}
It's possible if you haven't write permission where you currently trying. So you get an error when testing.
However you have made some few mistakes in code. reverseEachLine method was not worked and you should not waste code to create completeReverse method. Please note following things.
Construct the Scanner when you need it
Remember to close the Scanner
Write processed file after closing the Scanner
Remove append if not necessary in Filewriter
Remember to flush FileWriter
Identify similarities and relationships between methods (complete reverse is a combination of line reverse and word reverse)
public class MyReverser {
private File inputFile;
public MyReverser(File file) {
this.inputFile = file;
}
public void reverseLines(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new java.util.Scanner(inputFile);
List<String> wordsarraylist = new ArrayList<String>();
while (sc.hasNextLine()) {
wordsarraylist.add(sc.nextLine());
}
sc.close();
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, false);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
public void reverseEachLine(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(inputFile);
ArrayList<List<String>> wordsarraylist = new ArrayList<List<String>>();
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
List words = Arrays.asList(sentence.split(" "));
Collections.reverse(words);
wordsarraylist.add(words);
}
FileWriter writer = new FileWriter(outpr, false);
for (List<String> list : wordsarraylist) {
for (String string : list) {
writer.append(string + " ");
}
writer.append(System.lineSeparator());
}
writer.flush();
writer.close();
}
public void completeReverse(File outpr) throws FileNotFoundException, IOException {
//reverse lines first
reverseLines(outpr);
//then reverse words
reverseEachLine(outpr);
}
}
The scenario here was the scanners were instance variables and once read in one of your operations method, it won't have more to read when you call the next method from Demo class. Have made the changes to read the sentences and store it in the instance, so that it can be reused in each method.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc = null;
Scanner sc2 = null;
boolean hasReadFile;
List<String> fileLinesList;
// constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file) throws FileNotFoundException, IOException {
sc = new Scanner(file);
hasReadFile = false;
fileLinesList = new ArrayList<>();
}
// this method reverses the order of the lines in the output
// prints to output file specified in argument.
public void reverseLines(File outpr) throws FileNotFoundException,
IOException {
List<String> wordsarraylist = new ArrayList<String>();
readFile();
for (String sentence : fileLinesList) {
wordsarraylist.add(sentence);
}
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
// this method reverses the order of the words in each line of the input
// and prints it to output file specified in argument.
public void reverseEachLine(File outpr) throws FileNotFoundException,
IOException {
readFile();
for (String sentence : fileLinesList) {
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(
Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
}
private void readFile() {
if (!hasReadFile) {
while (sc.hasNextLine()) {
fileLinesList.add(sc.nextLine());
}
fileLinesList = Collections.unmodifiableList(fileLinesList);
hasReadFile = true;
}
}
// this methhod reverses the order of the words in each sentence of the
// input
// then writes it to output file specified in argument
// then uses the output file as input and reverses the order of the
// sentences
// then overwrites the ouput file with the result
// the output file will contain the input sentences with their words
// reversed
// and the order of sentences reversed.
public void completeReverse(File outpr) throws FileNotFoundException,
IOException {
readFile();
for (String sentence : fileLinesList) {
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist2 = new ArrayList<String>(
Arrays.asList(words));
Collections.reverse(wordsarraylist2);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist2) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
sc2 = new Scanner(outpr);
List<String> wordsarraylist = new ArrayList<String>();
while (sc2.hasNextLine()) {
wordsarraylist.add(sc2.nextLine());
}
Collections.reverse(wordsarraylist);
PrintWriter erase = new PrintWriter(outpr);
erase.print("");
// erase.flush();
erase.close();
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
}
I have to write a program that supports extensions. I have a problem with FileNotFound Exception. Program asks about the name of the file. My task is to write an special information when there is no file like given, and ask again until user will write an existing file name. I know how to write an special information that there is no file, but I don't know how to ask again about the name of the file (I only know that it must be done using readNP method).
Here is the code:
import.java.io.*;
import java.util.* ;
class Reading{
static BufferedReader sysin =
new BufferedReader(new InputStreamReader(System.in));
String readNP() throws IOException{
// ask about file name
System.out.print("file name ");
String filename;
filename = sysin.readLine() ;
return filename.trim();
}
void read(ArrayList<Double> a) throws IOException{
// reading from file
int nr=1 ;
String name = readNP();
BufferedReader br = new BufferedReader(new FileReader(name));
String line;
while ((line = br.readLine()) != null){
a.add(new Double(line));
nr++;
}
br.close() ;
}
}
class Exceptions{
static void average(ArrayList<Double> a){
double s=0.0d;
for (int i=0; i<a.size(); i++)
s+=a.get(i).doubleValue();
System.out.println("average from numbers in table: "+s/a.size());
}
public static void main(String[] args)throws IOException{
ArrayList<Double> a = new ArrayList<Double>();
Reading r = new Reading();
try{
r.read(a);
average(a);
} catch(FileNotFoundException e){
System.out.println("File not found");
}
}
}
I would add test for existence of file name (and for that it's not the name of the directory) into your readNP() function:
String readNP() throws IOException{
// ask about file name
for (;;) {
System.out.print("file name ");
String filename;
filename = sysin.readLine();
File f = new File(filename);
if (f.exists() && !f.isDirectory()) return filename.trim();
System.out.println("file absent"); //message if the there is no file with this name
}
}
How can I find and replace a word in several text files, using Java?
Here's how I do it for a single String...
public class ReplaceAll {
public static void main(String[] args) {
String str = "We want replace replace word from this string";
str = str.replaceAll("replace", "Done");
System.out.println(str);
}
}
Using FileUtils from Commons IO:
String[] files = { "file1.txt", "file2.txt", "file3.txt" };
for (String file : files) {
File f = new File(file);
String content = FileUtils.readFileToString(new File("filename.txt"));
FileUtils.writeStringToFile(f, content.replaceAll("hello", "world"));
}
You can read in the file using a FileReader wrapped by a BufferedReader, pulling it in line by line, perform the same replace on the string that you show in your question, and write it back out to a new file.
This is the working code: Hope it helps!
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TestIO {
static StringBuilder sbword = new StringBuilder();
static String dirname = null;
static File[] filenames = null;
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws FileNotFoundException, IOException{
boolean fileread = ReadFiles();
sbword = null;
System.exit(0);
}
private static boolean ReadFiles() throws FileNotFoundException, IOException{
System.out.println("Enter the location of folder:");
File file = new File(sc.nextLine());
filenames = file.listFiles();
String line = null;
for(File file1 : filenames ){
System.out.println("File name" + file1.toString());
sbword.setLength(0);
BufferedReader br = new BufferedReader(new FileReader(file1));
line = br.readLine();
while(line != null){
System.out.println(line);
sbword.append(line).append("\r\n");
line = br.readLine();
}
ReplaceLines();
WriteToFile(file1.toString());
}
return true;
}
private static void ReplaceLines(){
System.out.println("sbword contains :" + sbword.toString());
System.out.println("Enter the word to replace from each of the files:");
String from = sc.nextLine();
System.out.println("Enter the new word");
String To = sc.nextLine();
//StringBuilder sbword = new StringBuilder(stbuff);
ReplaceAll(sbword,from,To);
}
private static void ReplaceAll(StringBuilder builder, String from, String to){
int index = builder.indexOf(from);
while(index != -1){
builder.replace(index, index + from.length(), to);
index += to.length();
index = builder.indexOf(from,index);
}
}
private static void WriteToFile(String filename) throws IOException{
try{
File file1 = new File(filename);
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(file1));
bufwriter.write(sbword.toString());
bufwriter.close();
}catch(Exception e){
System.out.println("Error occured while attempting to write to file: " + e.getMessage());
}
}
}
I want to restore the following data from the text file. The problem is only one string/line I can restore, I can't restore the rest of the data.
Here's the code :
public static String restore(String filename) throws IOException, ClassNotFoundException
{
FileInputStream fn = new FileInputStream(filename);
ObjectInputStream ob = new ObjectInputStream(fn);
String sample = (String) ob.readObject();
return sample;
}
It is hard to understand the meaning of this question, but if you just want to read lines from a .txt file and into an array, then these two methods might help.
You just need to call String[] textArray = readFromFile("yourfilename.txt");
This gives you an array with each line in the file as an element.
Scanner fScan(String filename) {
Scanner sc = null;
try {
sc = new Scanner(new File(fname));
} catch (FileNotFoundException e) {
System.out.println("File not found:" + fname + " " + e);
}
return sc;
}
String[] readFromFile (String fname) {
Scanner sc = fScan(fname);
int length = 0;
String lineCounter;
while (sc.hasNext()){
lineCounter = sc.nextLine();
length++;
}
String[] array = new String[length];
sc = fScan(fname);
for (int i = 0; i < length; i++) {
array[i] = sc.nextLine();
}
sc.close();
return array;
}
Your code does only read the first Element within your binary file.
public static void restore(String filename) throws IOException, ClassNotFoundException
{
FileInputStream fn = new FileInputStream(filename);
ObjectInputStream ob = new ObjectInputStream(fn);
String string1 = (String) ob.readObject();
String string2 = (String) ob.readObject();
}
Are you sure you did not overwrite your file while serializing it?
But as far as I understand your Question you don't want to serialize/deserialize a String-Object, rather than reading/writing a textfile.
If you just want to read/write a file, you are on the wrong way with the ObjectInputStream.
ake a look at:
http://download.oracle.com/javase/1.3/docs/api/java/io/BufferedReader.html