I have a hdd array with 4 encrypted hard-drives (truecrypt). I recently switched back from 5 years of linux to windows 7 and I find myself confronted with a problem I can't find a solution for.
Under linux there was a command called "fdisk" which gives you all running (not mounted!) harddrives plus a unique disk-identifier which doesn't change (something like: Disk Identifier: 00x33f1a3c1).
I need that same functionality under Windows, preferably writing the code in java.
cheers
edit:// For clarification, I need the Disk-ID without mounting the Disk!
A solution using VBS.
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DiskUtils {
private DiskUtils() { }
public static String getSerialNumber(String drive) {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
+"Set colDrives = objFSO.Drives\n"
+"Set objDrive = colDrives.item(\"" + drive + "\")\n"
+"Wscript.Echo objDrive.SerialNumber";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}
public static void main(String[] args){
String sn = DiskUtils.getSerialNumber("C");
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, sn, "Serial Number of C:",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
Related
Good afternoon people,
With the help of research I did the code below to read texts of images:
package pckLeitor;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class Tess4jOCRv2 {
public static void main(String[] args) throws TesseractException {
File repository = new File("C:\\Users\\RAFSOUZA\\Desktop\\OCRTest");
try
{
for (File file : repository.listFiles()) {
String dtNow = new SimpleDateFormat("ddMMyyyy_HHmmss").format(Calendar.getInstance().getTime());
Tesseract tesseract = new Tesseract();
tesseract.setDatapath("C:\\Users\\RAFSOUZA\\Desktop\\Rafa3lOneiL\\BibliotecasExternasJAVA\\TesseractORC\\");
String fullText = tesseract.doOCR(file);
String fileExit = "C:\\Users\\RAFSOUZA\\Desktop\\OCRTest" + dtNow + ".txt";
FileWriter fstream = new FileWriter(fileExit);
BufferedWriter out = new BufferedWriter(fstream);
out.write(fullText);
out.newLine();
out.close();
}
}
catch (Exception e)
{
System.out.println("Ocorreu o seguinte erro" + e);
}
}
}
I would like to improve this code for:
1) Read all images in a folder
2) Generate a txt file with the data read from each image
Can you give me a direction?
Okay, so you've already gotten the code to read an image and output all text, right?
Let's try and wrap that with a loop or something using File#listFiles() and we should be ok!
Something like this should work, note I wrote this in notepad and it has not been tested!
import java.io.File;
public class Tess4jOCR {
public static void main(String[] args) throws TesseractException {
File repository = new File("C:\\Users\\RAFSOUZA\\Desktop\\OCRTest");
try {
for (File file : repository.listFiles()) {
String dtNow = new SimpleDateFormat("ddMMyyyy_HHmmss").format(Calendar.getInstance().getTime());
Tesseract tesseract = new Tesseract();
tesseract.setDatapath("C:\\Users\\RAFSOUZA\\Desktop\\Rafa3lOneiL\\BibliotecasExternasJAVA\\TesseractORC\\");
String fullText = tesseract.doOCR(file);
//String file = "O:\\Operações\\MIS\\Csa_OCR" + dtNow + ".txt";
String file = "C:\\RegistroRS" + dtNow + ".txt";
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
//System.out.println(fullText);
out.write(fullText);
out.newLine();
out.close();
}
} catch (Exception e) {
System.out.println("Ocorreu o seguinte erro" + e);
}
}
}
Simply put all images you want to process in C:\\Users\\RAFSOUZA\\Desktop\\OCRTest (or whatever directory the repository variable is set to, and run it and it should output it to C:\\RegistroRS-<timestamp>.txt
Please note you may want to add additional logic to check filenames or maybe output the txt file in a name that's related to the original input so you don't reprocess things if you run the code more than once and you can easily tell which output came from which input.
I'm building a simple class in Java that return the serial number of disk of computer. So this is the code:
package utility;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestReadSerialNumber {
private TestReadSerialNumber() { }
public static String getSerialNumber(String drive) {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
+"Set colDrives = objFSO.Drives\n"
+"Set objDrive = colDrives.item(\"" + drive + "\")\n"
+"Wscript.Echo objDrive.SerialNumber"; // see note
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}
public static void main(String[] args){
String sn = TestReadSerialNumber.getSerialNumber("C");
System.out.println(sn);}
}
Now if I try to start this code from a Windows, I have the correct result. If I try to start this code on a Mac Computer, I don't have never string from getSerialNumber method.
I think that the problem is in the System Operation and my code is compatible only with Windows and not with Mac.
Then, how can I get the serial number by Mac computer ?
I am trying to display the contents of multiple rows in a text file. I can do it no problem with a single line, but I add another line and I'm not sure what I need to add to my code to make it move on to the next line. I need myValues[1] to be the same as myValues[n] only to be the second line in the file. I believe I need to se a new String as the next line but I'm not sure exactly how with this setup.
package a3;
import java.io.*;
public class A3
{
public static void main(String [] args)
{
String animals = "animals.txt";
String line = null;
try
{
FileReader fileReader = new FileReader(animals);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String aLine = bufferedReader.readLine();
String myValues[] = aLine.split(" ");
int n = 0;
while((line = bufferedReader.readLine()) != null)
{
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
bufferedReader.close();
}
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + animals + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + animals + "'");
}
}
}
Here is another simple way to read lines from a file and do the processing:
There is a java.io.LineNumberReader class which helps do it.
Sample snippet:
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
String line = null;
while ((line = lnr.readLine()) != null)
{
// Do you processing on line
}
In your code, the array myValues is never changed and always contains the values for the first line of text. You need to change it each time you get a new line, this is done in your while loop :
[...]
while((line = bufferedReader.readLine()) != null)
{
myValues[] = line.split(" ");
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
Obviously not tested...
You could also read all lines to a String list like this:
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;
List<String> lines = Files.readAllLines(new File(animals).toPath(), Charset.defaultCharset());
And than iterate over the line list, split the values and output them.
Background
For a program I'm writing I need to be able to read Windows filenames from a file. Unfortunately, Windows use \ instead of /, which makes this tricky. I've been trying different ways, but it never seems to work. Here's the Java code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test {
static String localFile;
static String localFilePrefix;
static String user;
public static void main(String[] args){
readConfig("user.txt");
}
public static boolean readConfig(String cfgFilePath){
try{
BufferedReader reader = new BufferedReader(new FileReader(cfgFilePath));
try{
String line;
while((line = reader.readLine()) != null){
if(line.indexOf("User") != -1){
user = line.substring(line.indexOf(" ")+1);
}else if(line.indexOf("LocalFile") != -1){
String tmp = line.substring(line.indexOf(" ")+1);
System.out.println("Test: " + tmp);
setLocalFile(tmp);
}
}
}catch(IOException ee){
System.err.println(ee.getMessage());
}
}catch(FileNotFoundException e){
System.err.println(e.getMessage());
}
return true;
}
public static void setLocalFile(String lFileName){
System.out.println("FileName: " + lFileName);
localFile = lFileName;
if(new File(localFile).isDirectory()){
System.out.println("Here!");
localFilePrefix=localFile+File.separator;
}
}
}
And here is the config file:
User test
LocalFile C:\User
Running this code, whith that file path, doesn't print Test: C:\Users, which it should. Neither does it print FileName: C:\Users or Here!. If I remove "Users" from the file path, however, it works fine and prints everything it's supposed to. It even recognizes C:\ as a directory.
Question
I don't want the user to be forced to write the file path in a special format just because my program can't handle it. So how can I fix this?
Your first condition line.indexOf("User") != -1 is true for the input User test but also for LocalFile C:\User (and it will be so for every path that contains User). Therefore, the else if condition is not evaluated.
Use .startsWith instead of .indexOf
while ((line = reader.readLine()) != null) {
if (line.startsWith("User")) {
user = line.substring(line.indexOf(" ") + 1);
} else if (line.startsWith("LocalFile")) {
String tmp = line.substring(line.indexOf(" ") + 1);
System.out.println("Test: " + tmp);
setLocalFile(tmp);
}
}
I've got a text file called log.txt.
It's got the following data
1,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg
2,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg
The numbers before the first comma are indexes that specify each item.
What I want to do is to read the file and then replace one part of the string(e.g. textFiles/a.txt) in a given line with another value(e.g. something/bob.txt).
This is what I have so far:
File log= new File("log.txt");
String search = "1,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg;
//file reading
FileReader fr = new FileReader(log);
String s;
try (BufferedReader br = new BufferedReader(fr)) {
while ((s = br.readLine()) != null) {
if (s.equals(search)) {
//not sure what to do here
}
}
}
You could create a string of total file content and replace all the occurrence in the string and write to that file again.
You could something like this:
File log= new File("log.txt");
String search = "textFiles/a.txt";
String replace = "replaceText/b.txt";
try{
FileReader fr = new FileReader(log);
String s;
String totalStr = "";
try (BufferedReader br = new BufferedReader(fr)) {
while ((s = br.readLine()) != null) {
totalStr += s;
}
totalStr = totalStr.replaceAll(search, replace);
FileWriter fw = new FileWriter(log);
fw.write(totalStr);
fw.close();
}
}catch(Exception e){
e.printStackTrace();
}
One approach would be to use String.replaceAll():
File log= new File("log.txt");
String search = "textFiles/a\\.txt"; // <- changed to work with String.replaceAll()
String replacement = "something/bob.txt";
//file reading
FileReader fr = new FileReader(log);
String s;
try {
BufferedReader br = new BufferedReader(fr);
while ((s = br.readLine()) != null) {
s.replaceAll(search, replacement);
// do something with the resulting line
}
}
You could also use regular expressions, or String.indexOf() to find where in a line your search string appears.
Solution with Java Files and Stream
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
private static void replaceAll(String filePath, String text, String replacement) {
Path path = Paths.get(filePath);
// Get all the lines
try (Stream<String> stream = Files.lines(file, StandardCharsets.UTF_8)) {
// Do the replace operation
List<String> list = stream.map(line -> line.replace(text, replacement)).collect(Collectors.toList());
// Write the content back
Files.write(file, list, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.error("IOException for : " + file, e);
e.printStackTrace();
}
}
Usage
replaceAll("test.txt", "original text", "new text");
A very simple solution would be to use:
s = s.replace( "textFiles/a.txt", "something/bob.txt" );
To replace all occurrences, use replaceAll shown in another proposal, where a regular expression is used - take care to escape all magic characters, as indicated there.