How to load properties from xml file in java?

Input XML file

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<comment>Property details</comment>
	<entry key="location">bangalore</entry>
	<entry key="name">pretech</entry>
</properties>

Example

package com.pretech;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
public class JavaReadXMLProperties {
	public static void main(String[] args) {
		Properties pr = null;
		try {
			pr = new Properties();
			InputStream is = new FileInputStream("test.xml");
			pr.loadFromXML(is);
			is.close();
			System.out.println("Property values are ::");
			Enumeration<?> enumKeys = pr.keys();
			while (enumKeys.hasMoreElements()) {
				String key = (String) enumKeys.nextElement();
				String value = pr.getProperty(key);
				System.out.println(key + ":" + value);
			}
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

Output



Property values are ::
location:bangalore
name:pretech

How to convert Properties files to xml in java?

The Java.util.Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string. In this class storeToXML method helps to convert a stream to file. Here is one simple example to load a test properties file and converting in to xml file.

Input Property file (test.properties)

name=pretech
location=bangalore

Example

package com.pretech;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Properties;
public class JavaPropertiesToXML {
	public static void main(String[] args) {
		File file = null;
		try {
			System.out.println("Started conversion");
			file = new File("test.properties");
			FileInputStream fis = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			Properties pr = new Properties();
			pr.load(br);
			OutputStream os = new FileOutputStream("test.xml");
			pr.storeToXML(os, "Property details", "UTF-8");
			br.close();
			fis.close();
			os.close();
			System.out.println("Completed conversion");
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

Output (test.xml)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<comment>Property details</comment>
	<entry key="location">bangalore</entry>
	<entry key="name">pretech</entry>
</properties>

How to read contents of a jar file using JarInputStream ?

The JarInputStream class is used to read the contents of a JAR file from any input stream. Here is one simple example to read a jar and printing the jar contents.

JarInputStream Example

package com.pretech;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
public class JarInputStreamTest {
	public static void main(String[] args) {
		try {
			File file = new File("junit-4.11.jar");
			FileInputStream fis = new FileInputStream(file);
			JarInputStream jis = new JarInputStream(fis);
			JarEntry je;
			while ((je = jis.getNextJarEntry()) != null) {
				System.out.println(je.getName());
			}
			jis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output



junit/
junit/extensions/
junit/framework/
junit/runner/
junit/textui/
org/
org/junit/
org/junit/experimental/
org/junit/experimental/categories/
org/junit/experimental/max/
org/junit/experimental/results/
org/junit/experimental/runners/
org/junit/experimental/theories/
org/junit/experimental/theories/internal/
org/junit/experimental/theories/suppliers/
org/junit/internal/
org/junit/internal/builders/
org/junit/internal/matchers/
org/junit/internal/requests/
org/junit/internal/runners/
org/junit/internal/runners/model/
org/junit/internal/runners/rules/
org/junit/internal/runners/statements/
org/junit/matchers/
org/junit/rules/
org/junit/runner/
org/junit/runner/manipulation/
org/junit/runner/notification/
org/junit/runners/
org/junit/runners/model/
LICENSE.txt
junit/extensions/ActiveTestSuite$1.class
junit/extensions/ActiveTestSuite.class
junit/extensions/RepeatedTest.class
junit/extensions/TestDecorator.class
junit/extensions/TestSetup$1.class
junit/extensions/TestSetup.class
junit/extensions/package-info.class
junit/framework/Assert.class
junit/framework/AssertionFailedError.class
junit/framework/ComparisonCompactor.class
junit/framework/ComparisonFailure.class
junit/framework/JUnit4TestAdapter.class
junit/framework/JUnit4TestAdapterCache$1.class
junit/framework/JUnit4TestAdapterCache.class
junit/framework/JUnit4TestCaseFacade.class
junit/framework/Protectable.class
junit/framework/Test.class
junit/framework/TestCase.class
junit/framework/TestFailure.class
junit/framework/TestListener.class
junit/framework/TestResult$1.class
junit/framework/TestResult.class
junit/framework/TestSuite$1.class
junit/framework/TestSuite.class
junit/framework/package-info.class
junit/runner/BaseTestRunner.class
junit/runner/TestRunListener.class
junit/runner/Version.class
junit/runner/package-info.class
junit/textui/ResultPrinter.class
junit/textui/TestRunner.class
junit/textui/package-info.class
org/junit/After.class
org/junit/AfterClass.class
org/junit/Assert.class
org/junit/Assume.class
org/junit/Before.class
org/junit/BeforeClass.class
org/junit/ClassRule.class
org/junit/ComparisonFailure$ComparisonCompactor.class
org/junit/ComparisonFailure.class
org/junit/FixMethodOrder.class
org/junit/Ignore.class
org/junit/Rule.class
org/junit/Test$None.class
org/junit/Test.class
org/junit/experimental/ParallelComputer$1.class
org/junit/experimental/ParallelComputer.class
org/junit/experimental/categories/Categories$CategoryFilter.class
org/junit/experimental/categories/Categories$ExcludeCategory.class
org/junit/experimental/categories/Categories$IncludeCategory.class
org/junit/experimental/categories/Categories.class
org/junit/experimental/categories/Category.class
org/junit/experimental/max/CouldNotReadCoreException.class
org/junit/experimental/max/MaxCore$1$1.class
org/junit/experimental/max/MaxCore$1.class
org/junit/experimental/max/MaxCore.class
org/junit/experimental/max/MaxHistory$1.class
org/junit/experimental/max/MaxHistory$RememberingListener.class
org/junit/experimental/max/MaxHistory$TestComparator.class
org/junit/experimental/max/MaxHistory.class
org/junit/experimental/results/FailureList.class
org/junit/experimental/results/PrintableResult.class
org/junit/experimental/results/ResultMatchers$1.class
org/junit/experimental/results/ResultMatchers$2.class
org/junit/experimental/results/ResultMatchers$3.class
org/junit/experimental/results/ResultMatchers.class
org/junit/experimental/runners/Enclosed.class
org/junit/experimental/theories/DataPoint.class
org/junit/experimental/theories/DataPoints.class
org/junit/experimental/theories/ParameterSignature.class
org/junit/experimental/theories/ParameterSupplier.class
org/junit/experimental/theories/ParametersSuppliedBy.class
org/junit/experimental/theories/PotentialAssignment$1.class
org/junit/experimental/theories/PotentialAssignment$CouldNotGenerateValueException.class
org/junit/experimental/theories/PotentialAssignment.class
org/junit/experimental/theories/Theories$TheoryAnchor$1$1.class
org/junit/experimental/theories/Theories$TheoryAnchor$1.class
org/junit/experimental/theories/Theories$TheoryAnchor$2.class
org/junit/experimental/theories/Theories$TheoryAnchor.class
org/junit/experimental/theories/Theories.class
org/junit/experimental/theories/Theory.class
org/junit/experimental/theories/internal/AllMembersSupplier$1.class
org/junit/experimental/theories/internal/AllMembersSupplier$MethodParameterValue.class
org/junit/experimental/theories/internal/AllMembersSupplier.class
org/junit/experimental/theories/internal/Assignments.class
org/junit/experimental/theories/internal/ParameterizedAssertionError.class
org/junit/experimental/theories/suppliers/TestedOn.class
org/junit/experimental/theories/suppliers/TestedOnSupplier.class
org/junit/internal/ArrayComparisonFailure.class
org/junit/internal/AssumptionViolatedException.class
org/junit/internal/ComparisonCriteria.class
org/junit/internal/ExactComparisonCriteria.class
org/junit/internal/InexactComparisonCriteria.class
org/junit/internal/JUnitSystem.class
org/junit/internal/MethodSorter$1.class
org/junit/internal/MethodSorter$2.class
org/junit/internal/MethodSorter.class
org/junit/internal/RealSystem.class
org/junit/internal/TextListener.class
org/junit/internal/builders/AllDefaultPossibilitiesBuilder.class
org/junit/internal/builders/AnnotatedBuilder.class
org/junit/internal/builders/IgnoredBuilder.class
org/junit/internal/builders/IgnoredClassRunner.class
org/junit/internal/builders/JUnit3Builder.class
org/junit/internal/builders/JUnit4Builder.class
org/junit/internal/builders/NullBuilder.class
org/junit/internal/builders/SuiteMethodBuilder.class
org/junit/internal/matchers/StacktracePrintingMatcher.class
org/junit/internal/matchers/ThrowableCauseMatcher.class
org/junit/internal/matchers/ThrowableMessageMatcher.class
org/junit/internal/matchers/TypeSafeMatcher.class
org/junit/internal/requests/ClassRequest.class
org/junit/internal/requests/FilterRequest.class
org/junit/internal/requests/SortingRequest.class
org/junit/internal/requests/package-info.class
org/junit/internal/runners/ClassRoadie.class
org/junit/internal/runners/ErrorReportingRunner.class
org/junit/internal/runners/FailedBefore.class
org/junit/internal/runners/InitializationError.class
org/junit/internal/runners/JUnit38ClassRunner$1.class
org/junit/internal/runners/JUnit38ClassRunner$OldTestClassAdaptingListener.class
org/junit/internal/runners/JUnit38ClassRunner.class
org/junit/internal/runners/JUnit4ClassRunner$1.class
org/junit/internal/runners/JUnit4ClassRunner$2.class
org/junit/internal/runners/JUnit4ClassRunner.class
org/junit/internal/runners/MethodRoadie$1$1.class
org/junit/internal/runners/MethodRoadie$1.class
org/junit/internal/runners/MethodRoadie$2.class
org/junit/internal/runners/MethodRoadie.class
org/junit/internal/runners/MethodValidator.class
org/junit/internal/runners/SuiteMethod.class
org/junit/internal/runners/TestClass.class
org/junit/internal/runners/TestMethod.class
org/junit/internal/runners/model/EachTestNotifier.class
org/junit/internal/runners/model/MultipleFailureException.class
org/junit/internal/runners/model/ReflectiveCallable.class
org/junit/internal/runners/package-info.class
org/junit/internal/runners/rules/RuleFieldValidator.class
org/junit/internal/runners/statements/ExpectException.class
org/junit/internal/runners/statements/Fail.class
org/junit/internal/runners/statements/FailOnTimeout$StatementThread.class
org/junit/internal/runners/statements/FailOnTimeout.class
org/junit/internal/runners/statements/InvokeMethod.class
org/junit/internal/runners/statements/RunAfters.class
org/junit/internal/runners/statements/RunBefores.class
org/junit/matchers/JUnitMatchers.class
org/junit/matchers/package-info.class
org/junit/package-info.class
org/junit/rules/ErrorCollector$1.class
org/junit/rules/ErrorCollector.class
org/junit/rules/ExpectedException$ExpectedExceptionStatement.class
org/junit/rules/ExpectedException.class
org/junit/rules/ExpectedExceptionMatcherBuilder.class
org/junit/rules/ExternalResource$1.class
org/junit/rules/ExternalResource.class
org/junit/rules/MethodRule.class
org/junit/rules/RuleChain.class
org/junit/rules/RunRules.class
org/junit/rules/TemporaryFolder.class
org/junit/rules/TestName.class
org/junit/rules/TestRule.class
org/junit/rules/TestWatcher$1.class
org/junit/rules/TestWatcher.class
org/junit/rules/TestWatchman$1.class
org/junit/rules/TestWatchman.class
org/junit/rules/Timeout.class
org/junit/rules/Verifier$1.class
org/junit/rules/Verifier.class
org/junit/runner/Computer$1.class
org/junit/runner/Computer.class
org/junit/runner/Describable.class
org/junit/runner/Description.class
org/junit/runner/JUnitCore.class
org/junit/runner/Request$1.class
org/junit/runner/Request.class
org/junit/runner/Result$1.class
org/junit/runner/Result$Listener.class
org/junit/runner/Result.class
org/junit/runner/RunWith.class
org/junit/runner/Runner.class
org/junit/runner/manipulation/Filter$1.class
org/junit/runner/manipulation/Filter$2.class
org/junit/runner/manipulation/Filter$3.class
org/junit/runner/manipulation/Filter.class
org/junit/runner/manipulation/Filterable.class
org/junit/runner/manipulation/NoTestsRemainException.class
org/junit/runner/manipulation/Sortable.class
org/junit/runner/manipulation/Sorter$1.class
org/junit/runner/manipulation/Sorter.class
org/junit/runner/manipulation/package-info.class
org/junit/runner/notification/Failure.class
org/junit/runner/notification/RunListener.class
org/junit/runner/notification/RunNotifier$1.class
org/junit/runner/notification/RunNotifier$2.class
org/junit/runner/notification/RunNotifier$3.class
org/junit/runner/notification/RunNotifier$4.class
org/junit/runner/notification/RunNotifier$5.class
org/junit/runner/notification/RunNotifier$6.class
org/junit/runner/notification/RunNotifier$7.class
org/junit/runner/notification/RunNotifier$SafeNotifier.class
org/junit/runner/notification/RunNotifier.class
org/junit/runner/notification/StoppedByUserException.class
org/junit/runner/notification/package-info.class
org/junit/runner/package-info.class
org/junit/runners/AllTests.class
org/junit/runners/BlockJUnit4ClassRunner$1.class
org/junit/runners/BlockJUnit4ClassRunner.class
org/junit/runners/JUnit4.class
org/junit/runners/MethodSorters.class
org/junit/runners/Parameterized$Parameter.class
org/junit/runners/Parameterized$Parameters.class
org/junit/runners/Parameterized$TestClassRunnerForParameters.class
org/junit/runners/Parameterized.class
org/junit/runners/ParentRunner$1.class
org/junit/runners/ParentRunner$2.class
org/junit/runners/ParentRunner$3.class
org/junit/runners/ParentRunner$4.class
org/junit/runners/ParentRunner.class
org/junit/runners/Suite$SuiteClasses.class
org/junit/runners/Suite.class
org/junit/runners/model/FrameworkField.class
org/junit/runners/model/FrameworkMember.class
org/junit/runners/model/FrameworkMethod$1.class
org/junit/runners/model/FrameworkMethod.class
org/junit/runners/model/InitializationError.class
org/junit/runners/model/MultipleFailureException.class
org/junit/runners/model/NoGenericTypeParametersValidator.class
org/junit/runners/model/RunnerBuilder.class
org/junit/runners/model/RunnerScheduler.class
org/junit/runners/model/Statement.class
org/junit/runners/model/TestClass.class
org/junit/runners/package-info.class

How to upload file using Servlet 3.0 ?

javax.servlet.http.Part class represents a part as uploaded to the server as part of a multipart/form-data request body. The part may represent either an uploaded file or form data. Here is one simple example to upload file using Servlet 3.0

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form method="post" action="/FileUploadServletExample/fileupload" enctype="multipart/form-data">  
        Choose file <input type="file" name="file">
        <input type="submit" value="submit">
    </form>
</body>
</html>

FileUploadServlet.java

package com.pretech;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
 
@MultipartConfig         
@WebServlet("/fileupload")
public class FileUploadServlet extends HttpServlet {
 
	private static final long serialVersionUID = -7205406034336084784L;
	protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Part filePart = request.getPart("file");
        System.out.println("filename"+ filePart.getName());
        String fileName = getFileName(filePart);
        String fileLocation="c:/temp/";
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            File outputFilePath = new File(fileLocation + fileName);
            inputStream = filePart.getInputStream();
            outputStream = new FileOutputStream(outputFilePath);
            int read = 0;
            final byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        } catch (FileNotFoundException fne) {
            fne.printStackTrace();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } 
        response.setContentType("text/html;UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("File upload completed");     
        writer.close();
    }
 
    private String getFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim()
                        .replace("\"", "");
            }
        }
        return null;
    }
}

Output



image


image


Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts