I am using this java code to insert a txt file (which contain a java program) into MySQL database:
public static void main(String[] args) throws Exception {
String fileName = "copyEvens.txt";
FileInputStream fis = null;
PreparedStatement pstmt = null;
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
File file = new File(fileName);
fis = new FileInputStream(file);
pstmt = conn.prepareStatement("insert into code_table(language, code, passkey, program_name) values (?, ?, ?, ?)");
pstmt.setString(1, "java");
pstmt.setAsciiStream(2, fis, (int) file.length());
pstmt.setString(3, "ved");
pstmt.setString(4, "copyEvens");
pstmt.executeUpdate();
conn.commit();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
pstmt.close();
fis.close();
conn.close();
}
}
the txt file contain this program :
import java.util.Scanner;
public class copyEvens
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String str =in.nextLine();
int n = in.nextInt();
String []token = str.split(" ");
int array[] = new int[token.length];
for(int i=0; i<token.length; i++)
{
array[i] = Integer.parseInt(token[i]);
}
copyEvens obj = new copyEvens();
int result[] = obj.copyEvens(array, n);
for(int i: result)
{
System.out.print(i + " ");
}
System.out.println();
}
public int[] copyEvens(int[] nums, int count)
{
int l = 0;
int temp[] = new int[count];
for(int i=0; i<nums.length; i++)
{
if(nums[i]%2 == 0)
{
temp[l] = nums[i];
if(l!=(count-1))
l++;
else
break;
}
}
return temp;
}
}
but in the database it is not storing the full program as it is mentioned just above. It is storing only this much program like this:
import java.util.Scanner;
public class copyEvens
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String str =in.nextLine();
int n = in.nextInt();
String []token = str.split(" ");
int array[] = new int[token.length];
**for(int i=0; i**
After analyzing this I found that the program does not storing the things between this "<" ">" angular brackets. As, after this "for(int i=0; i" it should be "for(int i=0; i<token.length; i++)" and more..
Kindly help on this why it is not storing the content between angular brackets "<>".
You can try to dump the code directly into the database. If it is inserted as you expect (which there is absolutely no reason it shouldn't) then you will need to escape your data before inserting it. PHP has a htmlspecialchars function that does this for you but you will need to find an equivalent library that does this for Java - I had a quick scan online and found some messy code that does this but it was far too shoddy for me to recommend. to anyone :).
Related
I am reading a file with a disease name and its remedies. Therefore, i want to save the name as key and remedies in a set as the value. How can i reach that? It seems there is some problems in my code.
public static HashMap<String,Set<String>> disease = new HashMap <> ();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File ("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = null;
String [] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
public static <T> void display (Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item:items) {
line+= item.toString() + ",";
if (line.length()> LEN) {
line = "";
}
}
System.out.println(line + "]");
}
here is my code
cancer,pain,swelling,bleeding,weight loss
gout,pain,swelling
hepatitis A,discoloration,malaise,tiredness
thrombosis,high heart rate
diabetes,frequent urination
and here is what the txt contains.
In your code , you haven't initialized the remedies HashSet(thats why it is throwing NullPointerException at line number 14).
and second issue is : i is getting incremented by 1 and you are not checking with size of your pats array ( i > parts.length) .
I edited your code :
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<String>();
String[] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()&&parts.length>i) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0], remedies);
}
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.io.File;
import java.util.Set;
public class Solution {
public static HashMap<String, Set<String>> disease = new HashMap<>();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = new HashSet<>();
String [] parts = fin.nextLine().split(",");
for (int i=1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display(Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item : items) {
line += item.toString() + ",";
if (line.length() > LEN) {
line = "";
}
}
System.out.println(line + "]");
}
}
Here is full working code. As suggested by #Pratik that you forget to initialize HashSet that's why NullPointerException error was coming.
You have a few issues here:
no need for inner while loop (while (fin.hasNext()) {) - instead use `for(int i=1; i
HashSet <String> remedies = null; - this means the set is not initialized and we cannot put items in it - nede to change to: HashSet<String> remedies = new HashSet<>();
It is better practice to close() the file in the finally part
The 'display' method will delete the line (if it is longer than 80 characters) before printing it.
it is better to use StringBuilder when appending strings
So the corrected code would be:
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class TestSOCode {
public static HashMap<String,Set<String>> disease = new HashMap<>();
private static int LINE_LENGTH = 80;
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<>();
String[] parts = fin.nextLine().split(",");
disease.put(parts[0], remedies);
for (int i = 1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
fin.close();
} catch (Exception e) {
System.out.println("Error when closing file: " + e.getMessage());
}
}
Set<String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display (Set<T> items) {
if (items == null)
return;
StringBuilder line = new StringBuilder("[");
int currentLength = 1; // start from 1 because of the '[' char
for (T item:items) {
String itemStr = item.toString();
line.append(itemStr).append(",");
currentLength += itemStr.length() + 1; // itemStr length plus the ',' char
if (currentLength >= LINE_LENGTH) {
line.append("\n");
currentLength = 0;
}
}
// replace last ',' with ']'
line.replace(line.length() - 1, line.length(), "]");
System.out.println(line.toString());
}
}
package canlitahmin;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class baglanti {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/canlitahmin";
// Database credentials
static final String USER = "root";
static final String PASS = "";
public static List<Integer> id = new ArrayList<Integer>();
public static List<Integer> evgol = new ArrayList<Integer>();
public static List<Integer> kuralid = new ArrayList<Integer>();
public static List<String> kural = new ArrayList<String>();
public static List<Integer> depgol = new ArrayList<Integer>();
public static List<Integer> dakika = new ArrayList<Integer>();
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Statement stmt2 = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
stmt2 = conn.createStatement();
String sql;
String sql2;
sql = "SELECT id, evgol, depgol, dk FROM maclar";
sql2="SELECT id,kural from kurallar";
ResultSet rs = stmt.executeQuery(sql);
ResultSet rs2 = stmt2.executeQuery(sql2);
int i=0;
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
id.add(rs.getInt("id"));
evgol.add(rs.getInt("evgol"));
depgol.add(rs.getInt("depgol"));
dakika.add(rs.getInt("dk"));
//Display values
System.out.print("ID: " + id.get(i));
System.out.print(", Evgol: " + evgol.get(i));
System.out.print(", Depgol: " + depgol.get(i));
System.out.println(", dakika: " + dakika.get(i));
i++;
}
int k=0;
while(rs2.next()){
//Retrieve by column name
kuralid.add(rs2.getInt("id"));
kural.add(rs2.getString("kural"));
//Display values
System.out.print("KURALID: " + kuralid.get(k));
System.out.println(", KURAL: " + kural.get(k));
k++;
}
for(int l=0;l<id.size();l++){
int BYTG=evgol.get(l);
int DEPTG=depgol.get(l);
/* int DK=dakika.get(l);
int MACKODLARI=id.get(l);*/
for(int j=0;j<kuralid.size();j++){
###if(kural.get(j))###{ // ERROR**********************************
double a=BYTG+DEPTG+0.5;
int b=BYTG+DEPTG;
String kural="Tahmin:"+a+" üstü ve "+b+" üstü";
System.out.println(kural);
}}
}
//STEP 6: Clean-up environment
rs.close();
rs2.close();
stmt.close();
stmt2.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
java if statement string comparison. my database datas get in "kural.get(j)"
but kural.get(j) error. because its string variable.
Question: String a=b>0 && c>0 -- if(a) how i use? String code in if with variable
This can be done programmatically with the JavaCompiler and the javax.tools package
As a related question, see How do I programmatically compile and instantiate a Java class?
The solution is the same.
You cannot easily do that with Strings. What you can do is make an interface like this
interface IntIntPredicate {
public boolean test(int i, int j);
}
Then you can do (in Java 8):
IntIntPredicate a = (i, j) -> i == 1 && j <= 2;
IntIntPredicate b = (i, j) -> i <= 0 && j == 2;
Then later you can do:
if (a.test(i, j)) {
// do something
} else if (b.test(i, j)) {
// do something else
}
This is possible in earlier versions of Java, but the syntax is more clumsy.
If it is necessary for the data to be entered as a String, it would probably not be too difficult to write a method to parse a String (treating i and j as the first and second arguments) and return an IntIntPredicate
public static IntIntPredicate parse(String x) {
// This is going to require a lot of work, but
// there are many questions on this site about how
// to parse expressions such as "(2 + 3) * 9"
}
You could make a method, like:
boolean predicate(i,j) {
if (i==1 and j <=2) {
return true;
}
return false;
}
And then invoke the method like this:
if (predicate(i,j)) {
System.out.println("a");
}
You can also used ScriptEngine, but you need to translate the logic to a scripting language like Javascript.
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
/**
*
* #author afshin
*/
public class Blah {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
int i = 1;
int j = 1;
String a = i + "==1 && " + j +"<=2";
String b= i + "<=0 && " + j+"==2";
if (((Boolean) engine.eval(a)))
System.out.println("a is true");
if (((Boolean) engine.eval(b)))
System.out.println("b is true");
}
}
I have tried so hard to find a solution to this problem! Here is my code:
import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class Weather {
public static void main(String[] args) throws IOException {
//Getting the file.
String fileName = "weather2013.txt";
//Lines!
String line;
//Creating arrayList object
ArrayList aList = new ArrayList();
try {
BufferedReader input = new BufferedReader(new FileReader(fileName));
while ((line = input.readLine()) != null) {
aList.add(line);
}
//Close the file
input.close();
} catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
//Station ID Number:
String firstLine = aList.get(1).toString();
String stationIDStr = firstLine.substring(0, 6);
int StationID = Integer.parseInt(stationIDStr);
//System.out.println(StationID);
//WBAN ID Number:
String wbanIDstr = firstLine.substring(7, 12);
int wbanID = Integer.parseInt(wbanIDstr);
//System.out.println(wbanID);
//Year!
String yearStr = firstLine.substring(12, 18).trim();
int year = Integer.parseInt(yearStr);
//System.out.println(year);
//Remove line of text (not needed)
aList.remove(0);
//Fog days:
int fogDays = 0;
for (int i = 0; i < aList.size(); i++) {
String listString = aList.get(i).toString(); //iterate each readLINE -> String
String lastDigits = listString.substring(132, 137); //Each entry from 132-137 only
char fogIndicator = lastDigits.charAt(0);
if (fogIndicator == '1') {
fogDays++;
}
}
//System.out.println(fogDays);
//Maximum and minimum average temps
for (int i = 0; i < aList.size(); i++) {
String listString = aList.get(i).toString();
String averageTempDigits = listString.substring(24, 30).trim();
}
}
}
The specific part of the code where I am having trouble is the VERY last for loop.
Here's what's being outputted:
47.9
41.8
.
.
.
.
41.8
67.0
66.5
I would like to know how to get this column above into an Array or ArrayList?
i am doing a sample program where i need to get the values from database as example candidatename and to write a .txt file and this part is ok for me. my problem is in .txt file the name value is fixed length so i need to add some 0 before the name to fulfil that condition . for example my name lenght in .txt file is 10 char and if my name is "amar" then i need to add some 0 before the name as "0000000amar". i am attaching my code bellow
package com.myapp.struts.Action;
public class Main {
public static final long RECORD_LENGTH = 100;
public static final String EMPTY_STRING = " ";
public static final String CRLF = "\n";
public static void main(String[] argv) throws Exception {
String a="";
String q="";
PrintWriter writer=null;
try
{
File file=new File("c:/report");
file.mkdirs();
Connection connection = mbjBaseDAO.getConnection();
Statement stmt = connection.createStatement();
String query="select candidate_name from online_application ";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
a=rs.getString("candidate_name");
int lenght=a.length();
System.out.println("lenght is"+lenght);
System.out.println(q);
writer=new PrintWriter("c:/report/challan.txt");
for(int i=0;i<10;i++)
{
writer.print(q+"\t");
if((i)==i)
{
writer.println();
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
writer.flush();
writer.close();
}
}
public static String paddingRight(String source)
{
StringBuilder result = new StringBuilder(100);
if(source != null)
{
result.append(source);
for (int i = 0; i < RECORD_LENGTH - source.length(); i++)
{
result.append(EMPTY_STRING);
}
}
return result.toString();
}
}
Please help
String str = "amar";
str = String.format("%11s", str).replace(' ', '0');
System.out.println(str); // 0000000amar
I have this code that writes an object:
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
And this code that loads the object:
Model m = null;
try {
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m = (Model) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {}
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
I'm pretty sure that saving works, as when I opened the file in notepad++ I saw most of the data that I had saved, but when I load there is no data in module list.
Full source code:
import java.io.*;
import java.util.*;
public class Model implements java.io.Serializable {
private Student[] studentList = new Student[0];
private Module[] moduleList = new Module[0];
public void menu() {
while (true) {
System.out.println ("MENU");
System.out.println ("");
System.out.println (" 1 - Run Tests");
System.out.println (" 2 - Add Student");
System.out.println (" 3 - Add Module");
System.out.println (" 4 - Add Student To Module");
System.out.println (" 5 - Save System (Text file)");
System.out.println (" 6 - Load System (Text file)");
System.out.println (" 7 - Save System (Serialized)");
System.out.println (" 8 - Load System (Serialized)");
System.out.println (" 9 - Print Report");
System.out.println ("");
System.out.print ("Enter choice: ");
String input = keyboard.readString();
switch (input) {
case "1" :
runTests();
break;
case "2" :
System.out.print("First Name : ");
String fN = keyboard.readString();
System.out.print("Surname : ");
String sN = keyboard.readString();
System.out.print("Course Code : ");
String c = keyboard.readString();
System.out.print("User ID : ");
String iD = keyboard.readString();
AddStudent(iD, sN, fN, c);
break;
case "3" :
System.out.print("Module Code : ");
String code = keyboard.readString();
String[] temp = new String[0];
AddModule(code,temp);
break;
case "4" :
System.out.print("Module Code : ");
code = keyboard.readString();
Module m = findAModule(code);
if (m != null) {
System.out.print("User ID : ");
iD = keyboard.readString();
Student s = findAStudent(iD);
if (s != null) {
m.addThisStudent(s);
} else {
System.out.println("Student not found");
}
} else {
System.out.println("Module not found");
}
break;
case "5" :
saveToTextFiles();
break;
case "6" :
loadFromTextFiles();
break;
case "7" :
saveSerialized();
break;
case "8" :
break;
case "9" :
printReport();
break;
}
}
}
public void runTests() {
loadFromTextFiles();
saveSerialized();
printReport();
}
public void loadFromTextFiles() {
studentList = new Student[0];
moduleList = new Module[0];
try {
Scanner fileReader = new Scanner(new InputStreamReader(new FileInputStream("students.txt")));
int num = fileReader.nextInt(); fileReader.nextLine();
for (int i = 0; i < num; i++) {
String u = fileReader.nextLine();
String sn = fileReader.nextLine();
String fn = fileReader.nextLine();
String c = fileReader.nextLine();
AddStudent(u, sn, fn, c);
}
fileReader.close();
fileReader = new Scanner(new InputStreamReader(new FileInputStream("modules.txt")));
num = fileReader.nextInt(); fileReader.nextLine();
for (int i = 0; i < num; i++) {
String code = fileReader.nextLine();
int numOfStudents = fileReader.nextInt(); fileReader.nextLine();
String[] students = new String[numOfStudents];
for (int j = 0; j < numOfStudents; j++) {
students[j] = fileReader.nextLine();
}
AddModule(code, students);
}
fileReader.close();
} catch (IOException e) {}
}
public void saveToTextFiles () {
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("students.txt")));
outfile.println(studentList.length);
for (int i = 0; i < studentList.length; i++) {
outfile.println(studentList[i].getUID());
outfile.println(studentList[i].getSN());
outfile.println(studentList[i].getFN());
outfile.println(studentList[i].getDegree());
}
outfile.close();
outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("modules.txt")));
outfile.println(moduleList.length);
for (int i = 0; i < moduleList.length; i++) {
outfile.println(moduleList[i].getCode());
outfile.println(moduleList[i].getStudents().length);
for (int j = 0; j < moduleList[i].getStudents().length; j++) {
outfile.println(moduleList[i].getStudents()[j]);
}
}
outfile.close();
} catch (IOException e) {}
}
public void saveSerialized() {
try {
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
FileOutputStream fileOut2 = new FileOutputStream("Module.ser");
ObjectOutputStream out2 = new ObjectOutputStream(fileOut2);
out2.writeObject(studentList);
out2.close();
fileOut2.close();
FileOutputStream fileOut3 = new FileOutputStream("Student.ser");
ObjectOutputStream out3 = new ObjectOutputStream(fileOut3);
out3.writeObject(moduleList);
out3.close();
fileOut3.close();
} catch (IOException e) {}
}
public void loadSerialized() {
Model m = null;
try {
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m = (Model) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {}
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
}
private Module[] getModuleList() {
return moduleList;
}
private Student[] getStudentList() {
return studentList;
}
private void setModuleList(Module[] m) {
moduleList = m.clone();
}
private void setStudentList(Student[] s) {
studentList = s.clone();
}
private void AddModule(String code, String[] students) {
int length = moduleList.length;
Module NewArray[] = new Module[length + 1];
for (int i = 0; i < length + 1; i++) {
if (i < length) {
NewArray[i] = new Module(moduleList[i]);
}
}
NewArray[length] = new Module(code, students);
moduleList = NewArray.clone();
}
private void AddStudent(String u, String sn, String fn, String c) {
int length = studentList.length;
Student NewArray[] = new Student[length + 1];
for(int i = 0; i < length + 1; i++) {
if (i < length) {
NewArray[i] = new Student(studentList[i]);
}
}
NewArray[length] = new Student(u, sn, fn, c);
studentList = NewArray.clone();
}
public void printReport() {
for (int i = 0; i < moduleList.length; i++) {
System.out.println(moduleList[i].toString(this));
}
}
public Student findAStudent(String uid) {
for (int i = 0; i < studentList.length; i++) {
if (studentList[i].getUID().compareTo(uid) == 0) {
return studentList[i];
}
}
return null;
}
public Module findAModule(String code) {
for (int i = 0; i < moduleList.length; i++) {
if (moduleList[i].getCode().compareTo(code) == 0) {
return moduleList[i];
}
}
return null;
}
}
Look at your code sample, in particular the switch statement:
switch (input) {
...
case "8" :
break;
...
}
I'd assume the method loadSerialized should be called there but it's missing and is not called anywhere else in the code.
Once you actually call the method that does the loading, the code will work, assuming you have declared a serialVersionUID for both Student and Module.
Edit: why using serialization to persist objects is a bad idea
In simple terms, using serialization to persist objects is brittle.
An object's serialized form is tied to its class. Classes tend to change over time, meaning the serialized instance of the old cannot be loaded into the new.
While you can work round this by setting a serialVersionUID doing so introduces a reverse of the problem where, in the case new fields are introduced, the new cannot be read into objects of the old class, which can be a problem if you do rolling updates to the deployed system.
There's a host of other reasons - it's not easily readable (meaning you can't update it like you would a database or XML/JSON doc), it's inefficient, etc.