I like to add quotes inside a string gathered from the readLine() - java

The output is
INSERT INTO 'products'('productid', 'color', 'size', 'price') VALUES ('purse8901, red, small handbag, 70.00');
I would like to have the single straight quotes added so that I can import the converted sql file easily into the database again like this:
INSERT INTO 'products'('productid', 'color', 'size', 'price') VALUES
('purse8901', 'red', 'small handbag', '70.00');
The problem is that I can't figure out how to split the sCurrentLine string and add \' above.
package ConvertCSVtoSQL;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Convert {
public static void main(String[] args) throws IOException {
String begin = "INSERT INTO `produts`(`productid`, `color`. `size`,
`price`) VALUES ('";
File fileToSave = new File("C:\\Users\\Blue\\Desktop\\sql\
\products.sql");
if (!fileToSave.exists()) {
fileToSave.createNewFile();
}
FileWriter fw = new FileWriter(fileToSave.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write('\n');
String end = "');";
String sCurrentLine;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:\\Users\\Blue\\Desktop\
\products.csv"));
} catch (FileNotFoundException ex) {
Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null,
ex);
}
br.readLine();
for (int count = 1; count <= 236; count++) {
sCurrentLine = br.readLine();
bw.write(begin + sCurrentLine + end);
bw.write('\n');
}
bw.close();
}
}

May be you are looking for something like this:-
String name = "\'productid\'";

Related

How to print contents of a text to console as objects

Let's say I have theese words in a text file
Dictionary.txt
artificial
intelligence
abbreviation
hybrid
hysteresis
illuminance
identity
inaccuracy
impedance
impenetrable
imperfection
impossible
independent
How can I make each word a different object and print them on the console?
You can simple use Scanner.nextLine(); function.
Here is the following code which can help
also import the libraries
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
Use following code:-
String []words = new String[1];
try{
File file = new File("/path/to/Dictionary.txt");
Scanner scan = new Scanner(file);
int i=0;
while(scan.hasNextLine()){
words[i]=scan.nextLine();
i++;
words = Arrays.copyOf(words,words.legnth+1); // Increasing legnth of array with 1
}
}
catch(Exception e){
System.out.println(e);
}
You must go and research on Scanner class
This is a very simple solution using Files:
package org.kodejava.io;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
public class ReadFileAsListDemo {
public static void main(String[] args) {
ReadFileAsListDemo demo = new ReadFileAsListDemo();
demo.readFileAsList();
}
private void readFileAsList() {
String fileName = "Dictionary.txt";
try {
URI uri = Objects.requireNonNull(this.getClass().getResource(fileName)).toURI();
List<String> lines = Files.readAllLines(Paths.get(uri),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Source: https://kodejava.org/how-do-i-read-all-lines-from-a-file/
This is another neat solution using buffered reader:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 * BufferedReader and Scanner can be used to read
line by line from any File or
 * console in Java.
 * This Java program
demonstrate line by line reading using BufferedReader in Java
 *
 * #author Javin Paul
 */
public class BufferedReaderExample {
public static void main(String args[]) {
//reading file line by line in Java using BufferedReader
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream("C:/sample.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading
File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
fis.close();
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Source: https://javarevisited.blogspot.com/2012/07/read-file-line-by-line-java-example-scanner.html#axzz7lrQcYlyy
These are all good answers. The OP didn't state what release of Java they require, but in modern Java I'd just use:
import java.nio.file.*;
public class x {
public static void main(String[] args) throws java.io.IOException {
Files.lines(Path.of("/path/to/Dictionary.txt")).forEach(System.out::println);
}
}

save single string to array separate by multi space in file text java

I'm a java beginner and I'm doing a small project about dictionary, now I want to save word and translate mean in file, because my native language often have space like chicken will be con gà so, I must use other way, not by space, but I really don't know how to do that, a word and it translation in one line, separate by "tab", mean multi space like chicken con gà now I want to get 2 words and store it in my array of Words which I created before, so I want to do something like
w1=word1inline;
w2=word2inline;
Word(word1inline,word2inline);(this is a member of array);
please help me, thanks a lot, I just know how to read line from file text, and use split to get word but I am not sure how to read by multi space.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class docfile {
public static void main(String[] args)
{
String readLine;
ArrayList<String>str=new ArrayList<>(String);
try {
File file = new File("text.txt");
BufferedReader b = new BufferedReader(new FileReader(file));
while ((readLine = b.readLine()) != null) {
str.add()=readLine.split(" ");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you stick to using tabs as a separator, this should work:
package Application;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Application {
public static void main(String[] args) {
String line;
ArrayList<String> str = new ArrayList<>();
try {
File file = new File("text.txt");
BufferedReader b = new BufferedReader(new FileReader(file));
while ((line = b.readLine()) != null) {
for (String s : line.split("\t")) {
str.add(s);
}
}
str.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why not just use a properties file?
dict.properties:
chicken=con gá
Dict.java:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
public class Dict {
public static void main(String[] args) throws IOException {
Properties dict = new Properties();
dict.load(Files.newBufferedReader(Paths.get("dict.properties")));
System.out.println(dict.getProperty("chicken"));
}
}
Output:
con gá
If your line is like this chicken con gà you can use indexof() method to find the first space in the string.
Then you can substring each word by using substring() method.
readLine = b.readLine();
ArrayList<String>str=new ArrayList<>();
int i = readLine.indexOf(' ');
String firstWord = readLine.substring(0, i);
String secondWord = readLine.substring(i+1, readLine.length());
str.add(firstWord);
str.add(secondWord);

writeToFile is writing to file twice

I have tried out.append(s); However my problems grow out of control. Anyone else see anything my eyes are missing?
public void writeToFile()
{
PrintWriter out = null;
try
{
out = new PrintWriter(new BufferedWriter(new FileWriter("course.txt", true)));
for (String courseName:courseData.keySet())
{
Course course = courseData.get(courseName);
if (!course.isEmpty())
{
ArrayList<String> students = course.getStudentList();
for (String s : students)
{
out.println(courseName + "<<<<" + s);
}
}
else
{
out.println(courseName + "<<<<");
}
}
} catch (IOException ex)
{
Logger.getLogger(CourseApp.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
out.close();
}
}
My text file should look like this after I make an entry.
However this is the result I actually get.
//use pw.flush() at the end to avoid multiple copies
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.FileHandler;
public class MergeFiles {
public static void main(String[] arg) throws IOException
{
File dir=new File("E:\\videos\\assignments\\fileWork");
File file = new File("E:\\videos\\assignments\\fileWork\\MergeAllAssignments.txt");
file.getParentFile().mkdirs();
PrintWriter pw=new PrintWriter(file);
String[] fileNames=dir.list();
for(String files:fileNames)
{
System.out.println("Reading file "+files);
File f=new File(dir,files);//instance of file to read
BufferedReader br=new BufferedReader(new FileReader(f));//f>>filereader>>bufferedReader
String line=br.readLine();//reading line by line
while(line!=null)
{
System.out.println(line);
pw.println(line);
line=br.readLine();
}
pw.println("\r\n\n\r\n next days assignment>>>>>>>>>>>>>>>>>>>\r\n\r\n\r\n\r\n\r\n");
//to write everything in pw object to destinatio
}
pw.flush();
pw.close();
System.out.println("Copying completed");
}
}

Trying to append a text file using java printwriters

So I have a few other classes like this one, I call the method in using an object in the run file. I want to write every output of every class into the same text file. However at the moment only one output is being saved to the text file, as it is overwriting each time, how do I do this using a print writer seen below?
Any guidance is much appreciated!
Class:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class LineCounter {
public static void TotalLines() throws IOException {
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\Sam\\Desktop\\Report.txt"));
int linetotal = 0;
while (sc.hasNextLine()) {
sc.nextLine();
linetotal++;
}
out.println("The total number of lines in the file = " + linetotal);
out.close();
System.out.println("The total number of lines in the file = " + linetotal);
}
}
Run File:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class TextAnalyser {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
LineCounter Lineobject = new LineCounter();
WordCounter Wordobject = new WordCounter();
NumberCounter Numberobject = new NumberCounter();
DigitCounter Digitobject = new DigitCounter();
SpaceCounter Spaceobject = new SpaceCounter();
NumberAverage Noavgobject = new NumberAverage();
WordAverage Wordavgobject = new WordAverage();
Palindromes Palindromeobject = new Palindromes();
VowelCounter Vowelobject = new VowelCounter();
ConsonantCounter Consonantobject = new ConsonantCounter();
WordOccurenceTotal RepeatsObject = new WordOccurenceTotal();
Lineobject.TotalLines();
Wordobject.TotalWords();
Numberobject.TotalNumbers();
Digitobject.TotalDigits();
Spaceobject.TotalSpaces();
Noavgobject.NumberAverage();
Wordavgobject.WordAverage();
Vowelobject.TotalVowels();
Consonantobject.TotalConsonant();
Palindromeobject.TotalPalindromes();
//RepeatsObject.TotalRepeats();
}
}
You want to use the second argument of the FileWriter constructor to set the append mode:
new FileWriter("name_of_your_file.txt", true);
instead of:
new FileWriter("name_of_your_file.txt");

Getting arrayoutofbond error while running java code

I am getting arrayoutofbond error while running below given code,
sometime it is running as expected and sometime it is giving error.
Could anyone help me where I am wrong.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class getFileContent{
public void listFiles() throws IOException, InterruptedException{
File directory = new File("C:\\ScriptLogFile\\");
File[] myarray;
myarray=directory.listFiles();
int i=0;
ArrayList<String> arrayList = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_hhmmss");
Date curDate = new Date();
String strDate = sdf.format(curDate);
String fileName = strDate;
File file = new File("C:\\ExcelReport_"+fileName+".csv");
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bwr = new BufferedWriter(fileWritter);
String filename = null;
try {
for (int j = 0; j < myarray.length; j++)
{
File path=myarray[j];
FileInputStream fis = new FileInputStream (path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
if(path.isFile()){
if(path.getName().endsWith(".csv")){
filename = path.getName();
String line;
bwr.write(filename+",");
while ((line = br.readLine()) != null) {
if(line.contains("-")){
String[] part = line.split("-");
arrayList.add(part[1]);
bwr.write(arrayList.get(i)+",");
i++;
}
else{
}
}
bwr.write("\r\n");
}
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
bwr.close();
}
public static void main(String[] args) throws IOException, InterruptedException {
getFileContent gfc = new getFileContent();
gfc.listFiles();
}
}
We need a stack trace to see where the exception is raised. However you seem to be making assumptions about the length of part[]. Remember arrays are 0-indexed, the first entry would be at index 0 i.e. part[0]. Even then, in general there really needn't be many entries at all: "xyz".split("-") is an array of length 1 whose only element, "xyz", is at index 0.

Categories

Resources