This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
read/write to Windows Registry using Java
I want to read the registry value of the path HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Uninstall\{2FC099BD-AC9B-33EB-809C-D332E1B27C40}.
Can you please help me with the code?
This shows how to read the registry, but could be extended to write operations: How to read the Windows Registry
import java.io.*;
public class RegQuery {
private static final String REGQUERY_UTIL = "reg query ";
private static final String REGSTR_TOKEN = "REG_SZ";
private static final String REGDWORD_TOKEN = "REG_DWORD";
private static final String PERSONAL_FOLDER_CMD = REGQUERY_UTIL +
"\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\"
+ "Explorer\\Shell Folders\" /v Personal";
private static final String CPU_SPEED_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ~MHz";
private static final String CPU_NAME_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ProcessorNameString";
public static String getCurrentUserPersonalFolderPath() {
try {
Process process = Runtime.getRuntime().exec(PERSONAL_FOLDER_CMD);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String result = reader.getResult();
int p = result.indexOf(REGSTR_TOKEN);
if (p == -1)
return null;
return result.substring(p + REGSTR_TOKEN.length()).trim();
}
catch (Exception e) {
return null;
}
}
public static String getCPUSpeed() {
try {
Process process = Runtime.getRuntime().exec(CPU_SPEED_CMD);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String result = reader.getResult();
int p = result.indexOf(REGDWORD_TOKEN);
if (p == -1)
return null;
// CPU speed in Mhz (minus 1) in HEX notation, convert it to DEC
String temp = result.substring(p + REGDWORD_TOKEN.length()).trim();
return Integer.toString
((Integer.parseInt(temp.substring("0x".length()), 16) + 1));
}
catch (Exception e) {
return null;
}
}
public static String getCPUName() {
try {
Process process = Runtime.getRuntime().exec(CPU_NAME_CMD);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String result = reader.getResult();
int p = result.indexOf(REGSTR_TOKEN);
if (p == -1)
return null;
return result.substring(p + REGSTR_TOKEN.length()).trim();
}
catch (Exception e) {
return null;
}
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter();
}
public void run() {
try {
int c;
while ((c = is.read()) != -1)
sw.write(c);
}
catch (IOException e) { ; }
}
String getResult() {
return sw.toString();
}
}
public static void main(String s[]) {
System.out.println("Personal directory : "
+ getCurrentUserPersonalFolderPath());
System.out.println("CPU Name : " + getCPUName());
System.out.println("CPU Speed : " + getCPUSpeed() + " Mhz");
}
}
There's a tutorial that shows you without using Runtime.exec() function and uses specifically java.util.prefs.WindowsPreferences.
Related
The need:
I want to write data into compressed and normal format as well. When I'll have to write data into compressed format "useCompression" will be sent as "true" and "useCompression" will be false when data needs to be stored in normal(as it is given to the Writer class) format.
The problem here is, how will I identify whether the data is compressed or not later when Reader class is trying to read the data?
So, to solve the problem, I am writing "1" into file if is "useCompression" is true and "0" if "useCompression" is false.
writing is fine, but when we try to skip the first element using "fIn.skip(1)" cause it is the identifier and not actual data, it is leaving behind some garbage value.
For, example, I am trying to write "2019-07-31" into a file and "useCompression" is false, so my file will hold "02019-07-31" and post "fIn.skip(1)" call it should hold "2019-07-31" but it is holding "^#2019-07-31".
Please help me figure out what I am doing wrong here
I've tried to update Reader class's constructor as:
public Reader(String key)
{
mKey = key;
try {
FileInputStream fIn = new FileInputStream(streamFileForKey(key));
byte[] firstByte = new byte[1];
int read = fIn.read(firstByte);
boolean shouldUseDecompression = (1 == firstByte[0]);
if (shouldUseDecompression) {
mFin = new GZIPInputStream(fIn);
}
else {
mFin = fIn;
}
}
catch (Exception e) {
System.out.println("Failed to open (r) key " + key + " exception : " + e);
}
}
But it does not solve the problem.
The actual code is:
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.GZIPInputStream;
public class forStackOverflow {
public static void main(String []args) {
// Write to normal file
mReader1 = new Reader(mInputFileName);
mWriter1 = new Writer(mOutputFilename1, false);
int availableBytes = mReader1.availableBytes();
int readBytes = 1000;
while (availableBytes > 0)
{
if (availableBytes >= 1000) {
availableBytes = availableBytes - readBytes;
}
else {
readBytes = availableBytes;
availableBytes = availableBytes - readBytes;
}
mWriter1.write(mReader1.read(readBytes), 0, readBytes);
}
mReader1.close();
mWriter1.close();
}
private static File streamFileForKey(String key)
{
return new File(key);
}
static String mInputFileName = "~/Downloads/inputStream.txt";
static String mOutputFilename1 = "~/Downloads/outputStream.txt";
static Reader mReader1;
static Writer mWriter1;
private static class Writer
{
public Writer(String key, boolean useCompression) {
mKey = key;
try {
FileOutputStream fileOutput = new FileOutputStream(streamFileForKey(key));
if (useCompression) {
fileOutput.write(1);
gOutputStream = new GZIPOutputStream(fileOutput);
}
else {
fileOutput.write(0);
gOutputStream = new DataOutputStream(fileOutput);
}
}
catch (Exception e) {
System.out.println("Got error while opening stream for " + mKey + ". Ex: " + e);
}
}
public boolean write(byte[] bytes, int pos, int len)
{
boolean retVal = true;
if (gOutputStream == null) {
return false;
}
try {
gOutputStream.write(bytes, pos, len);
retVal = true;
}
catch (Exception e) {
System.out.println("Failed to write " + len + " bytes to key " +
mKey + e);
retVal = false;
}
return retVal;
}
public void close()
{
if (gOutputStream != null) {
try {
gOutputStream.close();
}
catch (Exception e) {
System.out.println("Failed to close key " + mKey + e);
}
gOutputStream = null;
}
}
private String mKey;
private OutputStream gOutputStream;
}
private static class Reader
{
public Reader(String key)
{
mKey = key;
try {
FileInputStream fIn = new FileInputStream(streamFileForKey(key));
if (shouldUseDecompression()) {
long skipped = fIn.skip(1);
mFin = new GZIPInputStream(fIn);
}
else {
long skipped = fIn.skip(1);
mFin = fIn;
}
}
catch (Exception e) {
System.out.println("Failed to open (r) key " + key + " exception : " + e);
}
}
public byte[] read(int len)
{
if (mFin == null) {
return null;
}
byte[] b = null;
try {
b = new byte[len];
int read;
read = mFin.read(b, 0, len);
if (read <= 0) {
return null;
}
}
catch (Exception e) {
System.out.println("Failed to read " + len + " bytes from key " +
mKey + " exception : " + e);
}
return b;
}
public void close()
{
if (mFin != null) {
try {
mFin.close();
}
catch (Exception e) {
System.out.println("Failed to close key " + mKey + " exception : " + e);
}
mFin = null;
}
}
private boolean shouldUseDecompression()
{
boolean retVal = false;
try {
FileInputStream fIn = new FileInputStream(streamFileForKey(mKey));
byte[] firstByte = new byte[1];
int read = fIn.read(firstByte);
// If first byte is `1` the we need to use decompression on it.
retVal = (1 == firstByte[0]);
fIn.close();
}
catch(Exception e) {
System.out.println("Exception in shouldUseDecompression() : " + e);
retVal = false;
}
return retVal;
}
public int availableBytes()
{
int available = 0;
try {
if (mFin != null) {
available = mFin.available();
}
}
catch (IOException e) {
System.out.println("Failed to read available bytes for " + mKey + ". Exception : " + e);
}
return available;
}
private String mKey;
private InputStream mFin;
}
}
The expected result should be, post "fIn.skip(1)" call file should hold "2019-07-31" and not "^#2019-07-31".
After a lot of struggle, I found out that it was the expected result.
^# was nothing but the binary 0 I was writing from Writer class's constructor incase useCompression was false.
From line fileOutput.write(0);.
I am trying to pass input to bash script using java input stream and collect bash script output to java output stream using two different thread.
my bash script is:
#!/bin/sh
echo "added at start"
while read LINE; do
echo $LINE
done
and my Java code is:
public class NewRedirector implements Runnable {
private static final int BULK_BUFFER_SIZE = 500000;
private static final int READ_BUFFER_SIZE = 250000;
private static final int OFFSET = 0;
private final OutputStream targetStream;
private final InputStream sourceStream;
private final boolean useChannel;
public NewRedirector(InputStream sourceStream , OutputStream targetStream, boolean useChannel) {
this.sourceStream = sourceStream;
this.targetStream = targetStream;
this.useChannel = useChannel;
}
#Override
public void run() {
byte[] readbyte = new byte[READ_BUFFER_SIZE];
int dataSize = 0;
try {
if(targetStream instanceof FileOutputStream && useChannel) {
FileChannel targetFC = ((FileOutputStream) targetStream).getChannel();
try {
if(sourceStream instanceof FileInputStream && useChannel) {
FileChannel sourceFC = ((FileInputStream) sourceStream).getChannel();
ByteBuffer bb = ByteBuffer.allocateDirect(BULK_BUFFER_SIZE);
bb.clear();
dataSize = 0;
while ((dataSize = sourceFC.read(bb)) > 0) {
bb.flip();
while (bb.hasRemaining()) {
targetFC.write(bb);
}
bb.clear();
}
} else {
ByteBuffer bb = ByteBuffer.allocateDirect(BULK_BUFFER_SIZE);
dataSize = 0;
while ((dataSize = sourceStream.read(readbyte)) > 0) {
if(BULK_BUFFER_SIZE > bb.position() + dataSize) {
bb.put(readbyte, OFFSET, dataSize);
continue;
} else {
bb.flip();
targetFC.write(bb);
bb.clear();
}
bb.put(readbyte, OFFSET, dataSize);
}
if(bb.position() > 0) {
bb.flip();
targetFC.write(bb);
bb.clear();
}
}
} catch(IOException e) {
System.out.println("Got Exception: " + e);
} finally {
if(targetFC != null && targetFC.isOpen()) {
targetFC.close();
targetFC = null;
}
}
} else {
BufferedOutputStream btarget = new BufferedOutputStream(targetStream);
try {
if (sourceStream instanceof FileInputStream && useChannel) {
FileChannel sourceFC = ((FileInputStream) sourceStream).getChannel();
ByteBuffer bb = ByteBuffer.allocateDirect(BULK_BUFFER_SIZE);
bb.clear();
dataSize = 0;
while ((dataSize = sourceFC.read(bb)) > 0) {
bb.position(OFFSET);
bb.limit(dataSize);
while (bb.hasRemaining()) {
dataSize = Math.min(bb.remaining(), READ_BUFFER_SIZE);
bb.get(readbyte, OFFSET, dataSize);
btarget.write(readbyte, OFFSET, dataSize);
}
btarget.flush();
bb.clear();
}
} else {
dataSize = 0;
while ((dataSize = sourceStream.read(readbyte)) > 0) {
btarget.write(readbyte, OFFSET, dataSize);
}
btarget.flush();
}
} catch(IOException e) {
System.out.println("Got Exception: " + e);
} finally {
if(btarget != null) {
btarget.close();
btarget = null;
}
}
}
} catch (IOException e) {
System.out.println("Got Exception: " + e);
}
}
}
and
public class NewProcessExecutor {
public static void main(String ... args) throws IOException, InterruptedException {
NewProcessExecutor pe = new NewProcessExecutor();
pe.startProcessinputfromstreamoutputtostreamintwothread();
}
private void startProcessinputfromstreamoutputtostreamintwothread()
throws IOException, InterruptedException {
String lscriptLocation = "/scratch/demo/RunScript/append.sh";
File inFile = new File("/scratch/demo/Source/inFile");
File outFile = new File("/scratch/demo/Source/outFile");
ProcessBuilder processBuilder = new ProcessBuilder(lscriptLocation);
/*processBuilder.redirectInput(Redirect.PIPE);
processBuilder.redirectOutput(Redirect.PIPE);*/
Process process = processBuilder.start();
if(Redirect.PIPE.file() == null && Redirect.PIPE.type() == Redirect.Type.PIPE) {
System.out.println("IO connected over PIPE");
}
//startStreamRedirector(new FileInputStream(inFile), process.getOutputStream());
startStreamRedirector(process.getInputStream(), new FileOutputStream(outFile));
int exitvalue = process.waitFor();
System.out.println("Exit value: " + exitvalue);
if (exitvalue != 0) {
System.out.println("Script execution failed with error: "
+ readErrorStream(process.getErrorStream()));
return;
} else {
System.out.println("Script executed successfully, please see output file: " + outFile.getAbsolutePath());
}
}
private String readErrorStream(InputStream errorStream) {
StringBuilder sb = new StringBuilder();
try (BufferedReader buffR = new BufferedReader(new InputStreamReader(
errorStream))) {
String line = null;
while ((line = buffR.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
System.out.println("Got Exception: " + e);
}
return sb.toString();
}
private void startStreamRedirector(InputStream inputStream, OutputStream outputStream) {
new Thread(new NewRedirector(inputStream, outputStream, true)).start();
}
}
Now the problem is this code sometime runs perfectly but some times it creates zero size file.
Can someone point out what could be the issue?
As per my information default redirect is PIPE so hope I don't need set redirect input and output to PIPE.
processBuilder.redirectInput(Redirect.PIPE)
I have return one script which on execution modifies a line in one file.
Flow for working script is from run method after printing checkpoint 111 it is going to executeCmd method after printing checkpoint aaaa, execution again goes to run method prints checkpoint 222 and comeback to executeCmd method and exit the execution after printing bbb.
But in my case after checkpoint aaa it is printing checkpoint bbb and this loop is never ending so execution is not going back to run method and hence script is stuck and hangs the session.
public String executeCmd(String classOpts, String cmdLine, String[] opts)
{
while (myCmd.isAlive() == true)
{
try
{
log.debug("checkpoint aaaa");
Thread.sleep(100);
log.debug("checkpoint bbbb");
}
}
exitVal = myCmd.getCmdExitValue();
log.debug("The script exit code: = " + exitVal);
}
public void run()
{
Runtime rt = Runtime.getRuntime();
try
{
String sCommand = cmdUtils.sScriptLauncher + " " + this.cmdline;
proc = rt.exec(cmdUtils.sScriptLauncher + " " + this.cmdline;
proc = rt.exec(cmdUtils.ParseCommandLine(sCommand));
try
{
log.debug("Checkpoint 111");
cmdExitVal = proc.waitFor();`enter code here`
log.debug("Checkpoint 222");
}
//remaining code
I use following class RunProcessCMD that uses ProcessBuilder, stdout and stderr:
class RunProcessCMD {
static BufferedReader stdout, stderr;
private Boolean isWaitFor = true;// wait for reply from CMD
private static RunProcessCMD startRunProcessCMD = null;
private String[] input = null;
private static boolean isRealTime = false;
private static StringBuilder buff = null;
public static RunProcessCMD getInstance(){
if(startRunProcessCMD == null){
startRunProcessCMD = new RunProcessCMD();
}
return startRunProcessCMD;
}
private RunProcessCMD(){}// destroy public constructor
public void start(String[] command) throws IOException {
buff = new StringBuilder();
System.out.println(Arrays.asList( command ) );
ProcessBuilder launcher = new ProcessBuilder();
launcher.redirectErrorStream(true);
launcher.command(command);
launcher.start(); // And launch a new process
buff.append("Done").append("\n");System.out.println("Done.");
}
public void start () throws IOException, InterruptedException{
buff = new StringBuilder();
if(input == null){
buff.append("Command == null");
return;
}
//String[] input = new String[] {"tasklist"};
Runtime r = Runtime.getRuntime();
//System.out.println("Execute ...");
//Process p = r.exec("cmd /c", input, null);
System.out.println(Arrays.asList( input ) );
Process p = r.exec(input);
//System.out.println("Finish to execute, start read output");
InputStream is = p.getInputStream();
stdout = new BufferedReader(new InputStreamReader(is));
is = p.getErrorStream();
stderr = new BufferedReader(new InputStreamReader(is));
//outputLines = new Vector();
if( isWaitFor == true ){
StdoutThread cltOut = RunProcessCMD.getInstance().new StdoutThread();
Thread tOut = new Thread(cltOut);
tOut.start();
StderrThread cltErr = RunProcessCMD.getInstance().new StderrThread();
Thread tErr = new Thread(cltErr);
tErr.start();
p.waitFor();
}
buff.append("Done").append("\n");System.out.println("Done.");
if( isWaitFor == false ){
buff.append("WaitFor defined to be false, respectivally no output from CMD").append("\n");
System.out.println("WaitFor defined to be false, respectively no output from CMD");
}
}
private class StdoutThread implements Runnable {
#Override
public void run() {
try {
int l;
String line;
for(l = 0; (line = stdout.readLine()) != null; ) {
if (line.length() > 0)
l++;
//outputLines.addElement(line);
buff.append(line).append("\n");
if(!line.trim().equals("")){
System.out.println(line);
}
}
stdout.close();
}
catch(IOException ie) {
buff.append("IO exception on stdout: " + ie).append("\n");
}
}
}
private class StderrThread implements Runnable {
public StderrThread() {}
#Override
public void run() {
try {
int l;
String line;
for(l = 0; (line = stderr.readLine()) != null; ) {
if (line.length() > 0) l++;
buff.append(line).append("\n");
System.out.print(line);
}
stderr.close();
}
catch(IOException ie) {
buff.append("IO exception on stdout: " + ie).append("\n");//System.out.println("IO exception on stdout: " + ie);
}
}
}
public static void ClearBuff (){
buff.setLength(0);
isRealTime = false;
}
public void setInput(String[] input) {
// reset flag
isWaitFor = true;
if(input[input.length-1].contains("waitFor") && input[input.length-1].split("=").length == 2 ){
String bull = input[input.length-1].split("=")[1];
isWaitFor = new Boolean( bull );
System.out.println("isWaitFor = " + isWaitFor);
// remove last value from String array
String[] input_new = new String[input.length -1];
for(int k=0; k < input_new.length; k++){
input_new[k] = input[k];
}
input = input_new;
}
// add proper value for input
String[] str = new String[input.length + 2];
str[0] = "cmd.exe";
str[1] = "/c";
for(int i=2; i<str.length; i++){
str[i] = input[i-2];
}
this.input = str;
}
public static StringBuilder getBuff() {
if( buff == null ){
return new StringBuilder( "" );
}
return buff;
}
public void setRealTime(boolean b) {
isRealTime = b;
}
}
Usage:
private void runSomeCommandOverCmd(){
String runP = "adb devices";
String[] strArr = new String[2];
strArr[0] = runP;
strArr[1] = "waitFor=true";
RunProcessCMD.getInstance().setInput( strArr );
try {
RunProcessCMD.getInstance().start();
String str = ( RunProcessCMD.getBuff() ).toString();
System.out.println(str);
RunProcessCMD.ClearBuff();
} catch (Exception e) {
try {
throw new Exception( "Failed to Start process CMD" );
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
my text
is like that
SEHiR;iL;iLCE;Tip;22356
S SI n;ISTA;ANK;A:S;22356
K K n;IS:TA;BB;B:S;22356
A A b;IS.TA;CC;DK;22356
G S b;ISTA;DD;O:P;22356
I want to change TIP column. I want to put "." instead of ":" for only Tıp column which include A:S,B:S etc.. And I want to write line before changing and after changing to csv. How can I do that? I write something but it has problem at
if(eD.tip.contains(":")) part because it dont continue to hS.Add(eD)
endeks.put("", hS); ı don’t want use “” string.
I do not have to use HasMap I could not write output what I want..
ı expected this output
S SI n;ISTA;ANK;A:S;22356
S SI n;ISTA;ANK;A.S;22356
K K n;IS:TA;BB;B:S;22356
K K n;IS:TA;BB;B.S;22356
G S b;ISTA;DD;O:P;22356
G S b;ISTA;DD;O.P;22356
public class MaliyeVknmDegil {
static class EndeksDegeri {
String sirket ;
String sehir;
String ilce;
String tip;
int numara;
}
static HashMap<String,HashSet<EndeksDegeri>> endeks = new HashMap<String, HashSet<EndeksDegeri>>();
static PrintWriter pW;
static EndeksDegeri eD = new EndeksDegeri();
static String satır;
private static PrintWriter pW2;
public static void main(String[] args) {
FileInputStream fIS;
FileOutputStream fOS;
try {
fIS = new FileInputStream("C:\\deneme\\DENEME.csv");
Reader r = new InputStreamReader(fIS, "UTF-8");
BufferedReader bR = new BufferedReader(r);
fOS = new FileOutputStream("c:\\yazdirilan\\deneme.csv");
Writer w = new OutputStreamWriter(fOS, "UTF-8");
pW2 = (new PrintWriter(w));
String satır;
String[] eleman;
while ((satır = bR.readLine()) != null) {
eleman = satır.split(";");
if(satır.contains(":")){
pW2.write(satır);
}
HashSet<EndeksDegeri> hS = new HashSet<EndeksDegeri>();
for (int i = 0; i < eleman.length; i++) {
// alteleman=eleman[i].split(" ");
EndeksDegeri eD = new EndeksDegeri();
eD.sirket = eleman[0];
eD.sehir = eleman[1];
eD.ilce = eleman[2];
if(eD.tip.contains(":")){
eD.tip.replaceAll(":", ".");
eD.tip = eleman[3];
}
eD.numara = Integer.parseInt(eleman[4]);
hS.add(eD);
}
endeks.put("", hS);
}
bR.close();
// yazdir
HashSet<EndeksDegeri> hS;
for (String s : endeks.keySet()) {
hS = endeks.get(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}// main end
}// clas end
package stackoverflow;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
public class TipChange {
private static String inputPath = "input.csv";
private static String outputPath = "output.csv";
private static BufferedReader bufferedReader;
private static PrintWriter printWriter;
public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream(inputPath);
Reader reader = new InputStreamReader(inputStream, "UTF-8");
bufferedReader = new BufferedReader(reader);
FileOutputStream outputStream = new FileOutputStream(outputPath);
Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
printWriter = new PrintWriter(writer);
String line;
while ((line = bufferedReader.readLine()) != null) {
EndeksDegeri eD = lineToClass(line);
if (shouldOutput(eD)) {
printWriter.append(classToLine(eD, true));
printWriter.append(classToLine(eD, false));
}
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
bufferedReader.close();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static boolean shouldOutput(EndeksDegeri eD) {
if (!eD.tip.contains(":")) {
return false;
}
return true;
}
private static String classToLine(EndeksDegeri eD, boolean original) {
if (!original) {
eD.tip = eD.tip.replace(":", ".");
}
return eD.sirket.concat(";")
.concat(eD.sehir).concat(";")
.concat(eD.ilce).concat(";")
.concat(eD.tip).concat(";")
.concat(String.valueOf(eD.numara)
.concat("\r\n"));
}
private static EndeksDegeri lineToClass(String line) {
String[] element = line.split(";");
EndeksDegeri endeksDegeri = new EndeksDegeri();
endeksDegeri.sirket = element[0];
endeksDegeri.sehir = element[1];
endeksDegeri.ilce = element[2];
endeksDegeri.tip = element[3];
endeksDegeri.numara = Integer.valueOf(element[4]);
return endeksDegeri;
}
private static class EndeksDegeri {
String sirket ;
String sehir;
String ilce;
String tip;
int numara;
}
}
Sample input:
SSI;ISTA;ANK;A:S;22356
KK;IS:TA;BB;B:S;22356
AA;IS.TA;CC;DK;22356
GS;ISTA;DD;O:P;22356
Generated Output:
SSI;ISTA;ANK;A:S;22356
SSI;ISTA;ANK;A.S;22356
KK;IS:TA;BB;B:S;22356
KK;IS:TA;BB;B.S;22356
GS;ISTA;DD;O:P;22356
GS;ISTA;DD;O.P;22356
Your code will produce a NullPointerException in the line: if(eD.tip.contains(":")){
That is because when a new EndeksDegeri instance is created all its fields are null you cannot call contains() on a null string.
Check the example code below (It writes to the console but it should get you going)
static class EndeksDegeri {
String sirket;
String sehir;
String ilce;
String tip;
int numara;
// I have added this method for convenience to write to the output
public String toString() {
return sirket + ":" + sehir + ":" + ilce + ":" + tip + ":" + numara;
}
}
while ((satir = bR.readLine()) != null) {
eleman = satir.split(";");
boolean found = false;
EndeksDegeri eD = new EndeksDegeri();
// first set all fields to not get exception
eD.sirket = eleman[0];
eD.sehir = eleman[1];
eD.ilce = eleman[2];
eD.tip = eleman[3];
eD.numara = Integer.parseInt(eleman[4]);
// check if the line contains ":"
if (eD.tip.contains(":")) {
// If yes, write the original line first
System.out.println(eD.toString());
// Change the record
eD.tip = eD.tip.replaceAll(":", ".");
found = true;
}
if (found) {
// write the corrected line now
System.out.println(eD.toString());
}
}
// Will print only the lines with ":" and its correct version
SSI:ISTA:ANK:A:S:22356
SSI:ISTA:ANK:A.S:22356
KK:IS:TA:BB:B:S:22356
KK:IS:TA:BB:B.S:22356
GS:ISTA:DD:O:P:22356
GS:ISTA:DD:O.P:22356
I am new to cryptography. I have to develop project based on cryptography..In part of my project I have to insert a key to the registry and afterwards I have to retrieve the same key for decryption.. I done until getting the path of the registry ..
Here I am showing my code:
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public final class Project {
public static final String readRegistry(String location, String key) {
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg query " +
'"' + location + "\" /v " + key);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String output = reader.getResult();
// Output has the following format:
// \n<Version information>\n\n<key>\t<registry type>\t<value>
if (!output.contains("\t")) {
return null;
}
// Parse out the value
String[] parsed = output.split("\t");
return parsed[parsed.length - 1];
} catch (Exception e) {
return null;
}
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw = new StringWriter();
public StreamReader(InputStream is) {
this.is = is;
}
public void run() {
try {
int c;
while ((c = is.read()) != -1) {
System.out.println("Reading" + c);
sw.write(c);
}
} catch (IOException e) {
System.out.println("Exception in run() " + e);
}
}
public String getResult() {
System.out.println("Content " + sw.toString());
return sw.toString();
}
}
public static boolean addValue(String key, String valName, String val) {
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg add \"" + key + "\" /v \"" + valName + "\" /d \"\\\"" + val + "\\\"\" /f");
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String output = reader.getResult();
System.out.println("Processing........ggggggggggggggggggggg." + output);
// Output has the following format:
// \n<Version information>\n\n<key>\t<registry type>\t<value>
return output.contains("The operation completed successfully");
} catch (Exception e) {
System.out.println("Exception in addValue() " + e);
}
return false;
}
public static void main(String[] args) {
// Sample usage
JAXRDeleteConcept hc = new JAXRDeleteConcept();
System.out.println("Before Insertion");
if (JAXRDeleteConcept.addValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU", "REG_SZ", "Muthus")) {
System.out.println("Inserted Successfully");
}
String value = JAXRDeleteConcept.readRegistry("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU" , "Project_Key");
System.out.println(value);
}
}
But i dont know how to insert a key in a registry and read the particular key which i inserted..Please help me..
Thanks in advance..
It would be a lot easier to use the JRegistry library to edit the registry, rather than execute commands.