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 ?
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 have a python script that searches the given search term on youtube and prints out the result on the console. When I run this script on cmd.exe it takes 2 seconds for it to print out the result but it does. However, I cannot capture the command line output on my Java code. It returns an empty ArrayList. I am one hundred percent sure that I execute the same command in my code as cmd.exe. What should I do to get the output of this script in my Java code? Thank you in advance.
Java Code:
package musicplayer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Wrapper {
public static ArrayList<String> search(String searchTerm) throws IOException {
String projectDirectory = System.getProperty("user.dir");
ArrayList<String> result = new ArrayList<>();
String[] commands = {"python", "'" + projectDirectory + "\\src\\python\\search.py'", "--q","\'"+ searchTerm +"\'"};
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = "";
while ((line = stdInput.readLine()) != null)
result.add(line);
return result;
}
public static void main(String[] args) {
try {
System.out.println(search("foo"));
} catch (IOException exc) {
exc.printStackTrace();
}
}
}
Python Script:
#!/usr/bin/python
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.tools import argparser
# valid developer key
DEVELOPER_KEY = "AIzaSyDvIqgHz4EQBm3qPRdonottrythisoneQ0W0Wooh5gYPQ8"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def youtube_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
q=options.q,
part="id,snippet",
maxResults=options.max_results
).execute()
videos = []
channels = []
playlists = []
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["videoId"]))
elif search_result["id"]["kind"] == "youtube#channel":
channels.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["channelId"]))
elif search_result["id"]["kind"] == "youtube#playlist":
playlists.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["playlistId"]))
print("Videos:\n", "\n".join(videos), "\n")
print("Channels:\n", "\n".join(channels), "\n")
print("Playlists:\n", "\n".join(playlists), "\n")
if __name__ == "__main__":
searchString = ''
argparser.add_argument("--q", help=searchString, default=searchString)
argparser.add_argument("--max-results", help="Max results", default=25)
args = argparser.parse_args()
try:
youtube_search(args)
except HttpError as e:
print ("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))
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 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);
}
}