I have a java class with a file path.When i try to run that as java application it is working fine but when i try to access that method in the class from a servlet I am getting error java.io.FileNotFoundException
Java Class
public class PropertiesManager {
static Properties prop =new Properties();
static String PROPERTY_FILENAME = "Dashboard1.0/src/server_url.properties";
public static void main(String[] args) {
loadProperty();
System.out.println(prop.getProperty("DemoApps_DataBase"));
updateProperty();
}
public static void loadProperty(){
InputStream input = null;
try {
FileInputStream file= new FileInputStream(PROPERTY_FILENAME);
// load a properties file
prop.load(file);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void updateProperty(){
OutputStream output = null;
try {
output = new FileOutputStream(PROPERTY_FILENAME);
// set the properties value
prop.setProperty("DemoApps_DataBase", "Oracle");
System.out.println(prop.getProperty("DemoApps_DataBase"));
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Servlet Class
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=request.getParameter("appName");
String link=request.getParameter("appLink");
String database=request.getParameter("appDB");
String webServices=request.getParameter("appWebService");
PropertiesManager.loadProperty();
PropertiesManager.updateProperty();
RequestDispatcher rd=request.getRequestDispatcher("updateappstatus.jsp");
rd.forward(request,response);
}
Related
Problem: if the path to the file was not specified in the arguments, then it still displays the phrase "The file was closed". This works 2 times. In uploadToFile and read method. I pass one path in the arguments, and the second is written in the DownloadFile
public class Task implements AutoCloseable {
public static void main(String[] args) throws IOException {
String DownloadFile = "C:\\Users\\VGilenko\\IdeaProjects\\Task\\src\\main\\resources\\Out.txt";
Map<String, Departament> departments = new HashMap<>();
String path = args.length > 0 ? args[0] : null;
read(path, departments);
transferToDepartment(departments, DownloadFile);
}
private static void uploadToFile(List download, String path) {
int i = 0;
try (FileWriter writer = new FileWriter(path, false)) {
...
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
} finally {
System.out.println("The file was closed");
}
}
public static void transferToDepartment(Map<String, Departament> departments, String downloadFile) {
List<String> download = new ArrayList<>();
...
}
uploadToFile(download, downloadFile);
}
public static void read(String path, Map<String, Departament> departments) throws IOException {
assert path != null;
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "CP1251")); br) {
.....
}
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found, check the path");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Correct the file path, step out of the array");
} catch (NullPointerException e) {
System.out.println("You forgot to register the path to the file");
} finally {
System.out.println("The file was closed");
}
}
#Override
public void close() {
System.out.println("The file was closed");
}
}
You have your printout "The file was closed" in your finally statement. If you don't specify a file, you will catch an Exception, and your finally block will be executed.
An easy fix would be to check for the existence of the path (not being empty, not being null).
I am writing one Java program which takes the jrxml file and compile the jrxml and then export the report to image in png format.
After that I am trying to print that image through zebra printer connected to my desktop. But it throws a net.sf.jasperreports.engine.JRRuntimeException exception during execution. I don't know what this error means.
Error log
Exception in thread "main" net.sf.jasperreports.engine.JRRuntimeException: Page index out of range: 0 of -1.
at net.sf.jasperreports.engine.JRAbstractExporter.getPageRange(JRAbstractExporter.java:804)
at net.sf.jasperreports.engine.export.JRGraphics2DExporter.exportReportToGraphics2D(JRGraphics2DExporter.java:302)
at net.sf.jasperreports.engine.export.JRGraphics2DExporter.exportReport(JRGraphics2DExporter.java:229)
at net.sf.jasperreports.engine.print.JRPrinterAWT.printPageToImage(JRPrinterAWT.java:288)
at net.sf.jasperreports.engine.JasperPrintManager.printToImage(JasperPrintManager.java:290)
at net.sf.jasperreports.engine.JasperPrintManager.printPageToImage(JasperPrintManager.java:446)
at com.greycode.optimization.Materialsin.generateReport(Materialsin.java:62)
Complete Java code:
public class Materialsin {
public static final void main(String[] args) throws FileNotFoundException {
Materialsin report = new Materialsin();
try {
report.generateReport(null, null);
} catch (JRException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ConnectionException e) {
e.printStackTrace();
} catch (ZebraPrinterLanguageUnknownException e) {
e.printStackTrace();
}
}
static JasperReport jasperReport = null;
public void generateReport(Map<String, Object> parameters, List<Label> labels)
throws JRException, IOException, ConnectionException, ZebraPrinterLanguageUnknownException {
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(labels);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
if (jasperPrint != null) {
FileOutputStream fos = new FileOutputStream("C:\\Users\\optimization\\Labels.png");
BufferedImage rendered_image = null;
rendered_image = (BufferedImage) JasperPrintManager.printPageToImage(jasperPrint, 0, 1.6f);
ImageIO.write(rendered_image, "png", fos);
try {
Connection thePrinterConn = new DriverPrinterConnection("GC420t",1000,1000);
thePrinterConn.open();
ZebraPrinter zPrinter = ZebraPrinterFactory.getInstance(thePrinterConn);
PrinterStatus printerStatus = zPrinter.getCurrentStatus();
if(printerStatus.isReadyToPrint) {
ZebraImageI image = ZebraImageFactory
.getImage("C:\\Users\\optimization\\Labels.png");
} else {
System.out.println("Something went wrong");
}
} finally {
}
}
}
static {
try {
jasperReport = JasperCompileManager
.compileReport(new FileInputStream("C:\\Users\\optimization\\Label.jrxml"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JRException e) {
e.printStackTrace();
}
}
}
Can anyone help me to fix this?
PropertiesConfiguration.java doesn't have a close() method. Is there something else that needs to be done to release the file? I want to be sure before I use this in production. I've looked through the code and I don't see anything. I'm not entirely sure how PropertiesConfiguration.setProperty() is working without opening a connection to the file that would then have to be closed.
In org.apache.commons.configuration.PropertiesConfiguration the input (stream, path, url, etc...) is of course closed when the properties were loaded in the PropertiesConfiguration instance.
You could have the confirmation in the void load(URL url) method of org.apache.commons.configuration.AbstractFileConfiguration.
Here is how this method is called :
1) PropertiesConfiguration constructor is invoked :
public PropertiesConfiguration(File file) throws ConfigurationException
2) which calls its super constructor :
public AbstractFileConfiguration(File file) throws ConfigurationException
{
this();
// set the file and update the url, the base path and the file name
setFile(file);
// load the file
if (file.exists())
{
load(); // method which interest you
}
}
3) which calls load() :
public void load() throws ConfigurationException
{
if (sourceURL != null)
{
load(sourceURL);
}
else
{
load(getFileName());
}
}
4) which calls load(String fileName):
public void load(String fileName) throws ConfigurationException
{
try
{
URL url = ConfigurationUtils.locate(this.fileSystem, basePath, fileName);
if (url == null)
{
throw new ConfigurationException("Cannot locate configuration source " + fileName);
}
load(url);
}
catch (ConfigurationException e)
{
throw e;
}
catch (Exception e)
{
throw new ConfigurationException("Unable to load the configuration file " + fileName, e);
}
}
5) which calls load(URL url)
public void load(URL url) throws ConfigurationException
{
if (sourceURL == null)
{
if (StringUtils.isEmpty(getBasePath()))
{
// ensure that we have a valid base path
setBasePath(url.toString());
}
sourceURL = url;
}
InputStream in = null;
try
{
in = fileSystem.getInputStream(url);
load(in);
}
catch (ConfigurationException e)
{
throw e;
}
catch (Exception e)
{
throw new ConfigurationException("Unable to load the configuration from the URL " + url, e);
}
finally
{
// close the input stream
try
{
if (in != null)
{
in.close();
}
}
catch (IOException e)
{
getLogger().warn("Could not close input stream", e);
}
}
}
And in the finally statement, you can see that the inputstream is closed in any case.
I have a requirement in my web application,i.e, to download data as csv from db, without creating a physical file in the server.So i've decided to write to outputstreame directly.
So what is the maximum bytes of data can i write to OutputStream.
my code is something like below.
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream os) throws IOException, WebApplicationException {
try {
-----------some code------
while(rs.next){
os.write(rs.getString(0).getBytes()+","+rs.getString(1).getBytes());
}
os.close();
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
import java.util.*;
import java.io.*;
public class BigFile{
public static void main(String asd[]){
String fileString = "D:/INSAn/error.log";
try {
BigFile bigFile = new BigFile(fileString);
for (String line : bigFile)
System.out.println("line : " + line);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("exception");
}
}
}
Hey you can use the above code , it will read file of any size.I tested it for 1 GB file.
I have desktop and android applications, which connected by bluetooth(in desktop side I use Bluecove 2.1.1 library). Desktop application create bluetooth service then android application connects to it. I want to add logout functionality from both desktop and android sides. For example in desktop app user click disconnect, both desktop and android apps reset their connections and should be able to connect again. Here is bluetoothService code for desktop side:
public class BluetoothService
{
private static final String serviceName = "btspp://localhost:"
// + new UUID("0000110100001000800000805F9B34F7", false).toString()
// + new UUID("0000110100001000800000805F9B34F8", false).toString()
+ new UUID("0000110100001000800000805F9B34F9", false).toString()
+ ";name=serviceName";
private StreamConnectionNotifier m_service = null;
private ListenerThread m_listenerThread;
private DataOutputStream m_outStream;
public BluetoothService()
{
Open();
}
public void Open()
{
try
{
assert (m_service == null);
m_service = (StreamConnectionNotifier) Connector.open(serviceName);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void Start()
{
try
{
StreamConnection connection = (StreamConnection) m_service
.acceptAndOpen();
System.out.println("Connected");
m_listenerThread = new ListenerThread(connection);
Thread listener = new Thread(m_listenerThread);
listener.start();
m_outStream = new DataOutputStream(connection.openOutputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Send(String message)
{
assert (m_listenerThread != null);
try
{
m_outStream.writeUTF(message);
m_outStream.flush();
System.out.println("Sent: " + message);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Close()
{
try
{
m_service.close();
m_listenerThread.Stop();
m_listenerThread = null;
m_outStream.close();
m_outStream = null;
m_service = null;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class ListenerThread implements Runnable
{
private DataInputStream m_inStream;
private boolean m_isRunning;
public ListenerThread(StreamConnection connection)
{
try
{
this.m_inStream = new DataInputStream(connection.openInputStream());
m_isRunning = true;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
;
}
public void run()
{
while (m_isRunning)
{
try
{
assert (m_inStream != null);
if (m_inStream.available() > 0)
{
String message = m_inStream.readUTF();
System.out.println("Received command: " + message);
CommandManager.getInstance().Parse(message);
}
}
catch (IOException e)
{
System.err.println(e.toString());
}
}
}
public void Stop()
{
m_isRunning = false;
try
{
m_inStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for restarting service I do:
BluetoothService::Close();
BluetoothService::Open();
BluetoothService::Start();
but seems I cannot reconnect. Maybe I should create service with different name?