I have 2 almost identical methods. But 1 can see my file , another not.It skips the method body with line = null. Dont understand why.
This doesnt work
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(#RequestParam("file") MultipartFile file, Model model) {
if (!file.isEmpty()) {
try {
String path = "d:/" + file.getOriginalFilename();
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(path)));
stream.write(bytes);
model.addAttribute("list", addRecordsToBD(path));
stream.close();
} catch (Exception e) {
log.error("Upload failed", e);
}
}
return "show";
}
private List addRecordsToBD(String path) {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
while ((line = reader.readLine()) != null) {
String[] users = line.split(",");
repository.saveAndFlush(new User(users[0], users[1], users[2],
users[3], users[4]));
}
} catch (IOException e) {
System.out.println("Input problems");
}
System.out.println("Inserting done");
return repository.findAll();
}
But this work great
public void addRecordsToBD(String path) {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
while ((line = reader.readLine()) != null) {
String[] users = line.split(",");
System.out.println("User [Name = " + users[0] +
", surname = " + users[1] +
" login = " + users[2] +
" mail = " + users[3] +
" phone = " + users[4] +
"]");
}
} catch (IOException e) {
System.out.println("Input problems");
}
System.out.println("Inserting done");
}
}
Can some one explain me, what's the problem and why this happened ?
Related
BufferedReader returns null and i don't understand why.
I have a ClientServer app with GUI interface and it works good, but in this method
idk why in loop msgFromServer has value = null because br.readline() returns it.
try {
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter pw = new PrintWriter(sock.getOutputStream(), true);
pw.println("refreshRoomOnClient");
countClientInRoomFromServer = br.readLine();
lblCountClientInRoom.setText("Clients in the room: " + countClientInRoomFromServer);
pw.println(txtNameRoom.getText());
listModelRoom.removeAllElements();
int size_listModelRoom = listModelRoom.size();
String msgFromServ;
while (!"exit".equals(msgFromServ = br.readLine())) {
System.out.println(msgFromServ);
if ("Cant find File".equals(msgFromServ)) {
txtLogs.append("Can't find files" + "\n");
break;
} else if ("error".equals(msgFromServ)) {
txtLogs.append("Error reading" + "\n");
break;
}
listModelRoom.insertElementAt(msgFromServ, size_listModelRoom);
}
} catch (IOException ex) {
txtLogs.append("btnRefreshCountClientInRoomActionPerformed..." + "\n");
}
I'm trying to adapt my code to Sonar and I don't get why I can't correct this blocker.
Its a 'Close this FileInputStream' with this starting code:
BufferedReader localBufferedReader = null;
try {
localBufferedReader = new BufferedReader( new InputStreamReader( new FileInputStream(inputFile),"UTF-8")); //THIS INPUTSTREAM!!
String line;
//
// Fill Hashmap
HashMap hmVar = (HashMap) this.context.getAttribute(this.hmVarName);
if (hmVar == null)
hmVar = new HashMap();
String[] props = new String[2];
while ((line = localBufferedReader.readLine()) != null) {
//Split line into key, value
if(line.startsWith("#"))
continue;
props = line.split("=");
hmVar.put(props[0], props[1]);
}
this.context.setAttribute(this.hmVarName, hmVar);
} catch (FileNotFoundException localException2) {
this.context.logError("Unable to find file: " + inputFile);
localException2.printStackTrace();
throw new WFException("Unable to find file: " + inputFile);
} catch (Exception localException4) {
this.context.logError("Exception reading file: " + inputFile
+ " (" + localException4.getMessage() + ")");
localException4.printStackTrace();
throw new WFException("Exception reading file: " + inputFile
+ " (" + localException4.getMessage() + ")");
} finally {
try {
if (localBufferedReader != null) {
localBufferedReader.close();
}
} catch (Exception localException5) {
}
}
So, ok. I declared apart the fileinputstream and go on, but it still doesn't like the way I close it.
BufferedReader localBufferedReader = null;
FileInputStream fis = null;
try {
//StringBuffer localStringBuffer = new StringBuffer();
fis = new FileInputStream(inputFile);
//localBufferedReader = new BufferedReader( new InputStreamReader( new FileInputStream(inputFile),"UTF-8")); SONAR correction FileInputStream needs to be closed
localBufferedReader = new BufferedReader( new InputStreamReader( fis,"UTF-8"));
String line;
//
// Fill Hashmap
HashMap hmVar = (HashMap) this.context.getAttribute(this.hmVarName);
if (hmVar == null)
hmVar = new HashMap();
String[] props = new String[2];
while ((line = localBufferedReader.readLine()) != null) {
//Split line into key, value
if(line.startsWith("#"))
continue;
props = line.split("=");
hmVar.put(props[0], props[1]);
}
this.context.setAttribute(this.hmVarName, hmVar);
} catch (FileNotFoundException localException2) {
this.context.logError("Unable to find file: " + inputFile);
localException2.printStackTrace();
throw new WFException("Unable to find file: " + inputFile);
} catch (Exception localException4) {
this.context.logError("Exception reading file: " + inputFile
+ " (" + localException4.getMessage() + ")");
localException4.printStackTrace();
throw new WFException("Exception reading file: " + inputFile
+ " (" + localException4.getMessage() + ")");
} finally {
try {
if (localBufferedReader != null) {
localBufferedReader.close();
}
if (fis != null) {
fis.close();
}
} catch (Exception localException5) {
}
}
Any ideas? I'm closing it the same way the BufferedReader that returns no issue.
Streams Readers and Writers implement the Closable interface. So you can get rid of the sonar warning if you use the try-with-resource construct:
try ( BufferedReader localBufferedReader = new BufferedReader( ...))
{
...
}
Any allocated Closable in the try (..) will be closed automatically if you leave the try block.
I am trying to serialize a DoccatModel Object in Java (I am using OpenNLP algorithm).
It's able to serialize the object properly and I am writing that to an external file. But, I'm not able to deserialise the object back.
I am trying to use ObjectInputStream to read that file back. It's throwing an error:
"java.io.StreamCorruptedException: invalid stream header: 504B0304"
I just want to know how to de serialize the DoccatModel object back so that I can use it further.
The code is as follows. [Apologies for bad code since its still in development stage]
private static void runDocCat(String textField, String updateField, String tgtField)
{
String dbName;
String tableName;
DoccatModel model = null;
JSONArray allDesc = null;
DataConfig BSC = null;
try
{
BSC = new DataConfig();
}
catch (Exception e1)
{
e1.printStackTrace();
}
try
{
dbName = BSC.getdbName();
tableName = BSC.tablename;
String dataQuery = "SELECT ID, VOC, " + tgtField + " from " + dbName + "." + tableName;
allDesc = BSC.getJSONArray(dataQuery);
File file = new File("voc.train");
BufferedWriter output = new BufferedWriter(new FileWriter(file));
for (int i = 0; i < allDesc.length(); i++)
{
String tgt = allDesc.getJSONObject(i).getString(tgtField);
if (tgt.length() < 3)
tgt = "Unknown";
tgt = tgt.replaceAll(" ", "");
String desc = allDesc.getJSONObject(i).getString(textField);
desc = desc.replaceAll("\\r", " ").replaceAll("\\n", ".");
if (!desc.trim().equalsIgnoreCase("nothing"))
{
DocumentSample currDoc = new DocumentSample(tgt, desc);
output.write(currDoc.toString());
output.newLine();
}
}
output.close();
System.out.println("Training Data Generated!");
ObjectStream<String> lineStream = new PlainTextByLineStream(new FileReader(file));
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
model = DocumentCategorizerME.train("en", sampleStream);
System.out.println("Model Data \n\n" + model);
// Write to a file
OutputStream modelOut = null;
try
{
String modelfile = "C:\\VOC_Classification\\model.ser";
modelOut = new BufferedOutputStream(new FileOutputStream(modelfile));
model.serialize(modelOut);
System.out.println("Model Data \n\n" + model);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (modelOut != null)
try
{
modelOut.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
// try
// {
// FileOutputStream fileOut = new FileOutputStream("modelfile.ser");
// ObjectOutputStream out = new ObjectOutputStream(fileOut);
// out.writeObject(model);
// out.close();
// fileOut.close();
// System.out.printf("Serialized data is saved in modelfile.ser");
// } catch (IOException i)
// {
// i.printStackTrace();
// }
DoccatModel model_SER = null;
try
{
FileInputStream fileIn = new FileInputStream("C:\\VOC_Classification\\model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
model_SER = (DoccatModel) in.readObject();
in.close();
fileIn.close();
} catch (IOException e)
{
e.printStackTrace();
}
System.out.println("\nTraining Done!\n");
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
System.out.println(" ---------- Starting categorising process ----------");
System.out.println("\nProcess Running, Please wait...\n");
for (int i = 0; i < allDesc.length(); i++)
{
dataQuery = "SELECT ID, VOC," + tgtField + " from " + dbName + "." + tableName;
allDesc = BSC.getJSONArray(dataQuery);
String ID = allDesc.getJSONObject(i).getString("ID");
String desc = allDesc.getJSONObject(i).getString(textField);
String newdesc = desc.replaceAll("\\n", ".").replaceAll("\\r", " ");
if (!newdesc.trim().equalsIgnoreCase("nothing"))
{
double[] outcomes = myCategorizer.categorize(newdesc);
String category = myCategorizer.getBestCategory(outcomes);
if (!category.equalsIgnoreCase("Unknown"))
{
String updQuery = "UPDATE " + dbName + "." + tableName + " set " + updateField + " = " + "'"
+ category + "'" + " WHERE ID = " + ID;
BSC.executeUpdate(updQuery);
}
}
}
System.out.println(" ---------- Process Completed Successfully ----------");
System.out.println("\nCheck your table \"" + tableName + "\" for results");
System.out.print("\n\nPress 1 to finish : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int ch = Integer.parseInt(br.readLine());
} catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
BSC.connectionClose();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The OpenNLP documentation is unclear, but there is a simple way of doing this.
private DoccatModel deSerializeModel(String modelPath) throws
IOException {
FileInputStream fileInputStream = new FileInputStream(modelPath);
DoccatModel model = new DoccatModel(fileInputStream);
return model;
}
I have this problem in my program:
When I do this:
double a = Double.parseDouble(zero);
double b = Double.parseDouble(data);
double c = a+b;
String d = Double.toString(c);
It returns me a String. For example, I have 0.0 in a and 4.0 in b and it returns 0.04.0.
Can someone explain to me why and what I should do instead?
EDITED: Here is my code:
private void WriteMedia(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("writemedia.txt", Context.MODE_PRIVATE));
String zero;
if(ReadMedia().isEmpty() == true)
{
zero = "0.0";
outputStreamWriter.write(zero);
}
else {zero = ReadMedia();}
double a = Double.parseDouble(zero);
double b = Double.parseDouble(data);
double c = a+b;
String d = Double.toString(c);
outputStreamWriter.write(d);
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String ReadMedia() {
String ret = "";
try {
InputStream inputStream = openFileInput("writemedia.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("estrela.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
WriteMedia(data);
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("estrela.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
WriteMedia(ret);
return ret;
}
The data is a ratingbar, zero is "0" when I start the app and it should save the rating bar to "increment"(don't know the english word). I thought it would be easy but since is like a bug just for me i'll put the tag android studio.
Here is where I call the method:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rating = ratingbar.getRating();
writeToFile(Double.toString(rating));
writeMyArray(Double.parseDouble(readFromFile()));
writeMyArray(ratingbar.getRating());
button.setText(getText(R.string.obrigado) + "!" + readFromFile() + " " + media(arraydays) + " " + ReadMedia());
}
});
It returns me the "0.0" and the ratingbar together, for example: "0.05.0"
Your problem is not related to types (other than you guessed) and it is not in the code you originally posted.
Instead, you are simply writing 2 numbers to your output stream. The following code writes 0.0:
if(ReadMedia().isEmpty() == true)
{
zero = "0.0";
outputStreamWriter.write(zero);
}
And, in addition to that, the following code writes the result you actually want:
double a = Double.parseDouble(zero);
double b = Double.parseDouble(data);
double c = a+b;
String d = Double.toString(c);
outputStreamWriter.write(d);
i am trying to use this code to replace field and after the replace is done i like to delete the file. But when i replace the file only 1 line was saved. How should i ensure that the other lines will be saved?
public static void main(String[] args){
AddChips();
}
public static void AddChips() {
File oldFile = new File ("players.dat");
File newFile = new File ("tempchips.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFile));
bw = new BufferedWriter(new FileWriter(newFile));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN)){
line = Username + "|" + Password + "|" + totalChips;
bw.write(line + System.getProperty("line.separator"));
}
//issue is here
br.close();
bw.close();
oldFile.delete();
newFile.renameTo(oldFile);
//AdminMenu();
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
}