Constructing image from Grayvalues - java

I have extracted the Gray Value from an image file (format .3pi) and wrote them in file (Code below)-
public class ImageFile {
public static void main(String[] args) throws IOException {
FileInputStream fstream = new FileInputStream ("Z:\\20100204-000083-011.3pi");
DataInputStream in = new DataInputStream (fstream);
BufferedReader reader = new BufferedReader (new InputStreamReader (in));
String str = "";
String temp [];
int counter = 0, NumberOfColumn = 0, NumberOfRow = 0;
try {
while (counter != 3) {
str = reader.readLine();
counter ++;
if (counter == 2) {
temp = str.split(" ");
NumberOfRow = Integer.valueOf(temp[5].trim()).intValue();
}
else if (counter == 3) {
temp = str.split(" ");
NumberOfColumn = Integer.valueOf(temp[3].trim()).intValue();
}
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
//System.out.println ("Row : "+NumberOfRow);
//System.out.println ("Column : "+NumberOfColumn);
int found = 0, CurrentColumn = 0, CurrentRow = 0, GrayValue;
int image [][] = new int [NumberOfRow][NumberOfColumn];
FileInputStream fstream2 = new FileInputStream ("Z:\\20100204-000083-011.3pi");
DataInputStream in2 = new DataInputStream (fstream2);
BufferedReader reader2 = new BufferedReader (new InputStreamReader (in2));
FileWriter fstream3 = new FileWriter("Z:\\Test.txt",true);
BufferedWriter writer = new BufferedWriter (fstream3);
while ((str = reader2.readLine()) != null) {
str = str.trim();
temp = str.split(" ");
if (temp [0].contentEquals("#:Profile:")) {
CurrentColumn = Integer.valueOf(temp[1].trim()).intValue();
//System.out.println ("Current Column : "+CurrentColumn);
found = 1;
continue;
}
else {
if (found == 1) {
CurrentRow = Integer.valueOf(temp[4].trim()).intValue();
GrayValue = Integer.valueOf(temp[3].trim()).intValue();
image [CurrentRow][CurrentColumn] = GrayValue;
}
}
}
for (int i= 0; i< NumberOfRow; i++){
for (int j= 0; j< NumberOfColumn; j++){
writer.write (image [i] [j]+" ");
}
writer.write("\n");
}
writer.close();
}
}
Now, I want to create a jpg/ bmp/ any other image with the Gray value information in Test.txt file. How can I achieve it? Help appreciated.
Zereen

The Java Image I/O API Guide should provide with a lot of useful information about image I/O in Java.
If you have pixel data (the colors you would like to use), you can use the class Graphics2D (part of AWT) to draw on a BufferedImage (part of AWT) as described here. You can then use ImageIO to write the data. So:
try {
BufferedImage off_Image =
new BufferedImage(100, 50, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = off_Image.createGraphics();
for (int i= 0; i< NumberOfRow; i++) {
for (int j= 0; j< NumberOfColumn; j++) {
g2.setColor(new Color(....)); // here convert the value in image[i][j] to aRGB
g2.draw(new Rectangle(i, j, 1, 1);
}
}
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
// handle exception
}

Related

Java File System Int or Double

I have 3 text files. Numbers.txt have int and double values like 1 1.5 2... I wanna put my int values to my Int.txt and double values to Double.txt.
So how can I do?
I tried .hasNextDouble() or .hasNextInt()
public static void main(String[] args) {
File f = new File("a.rtf");
File fWrite = new File("aWrite");
try {
FileReader fr = new FileReader(f);
FileWriter fw = new FileWriter(fWrite);
double c = fr.read();
while(c != -1){
char k = (char)c;
c.hasNextDouble();
System.out.print(k + " ");
fw.write((int) c);
c = fr.read();
}
fr.close();
fw.close();
} catch(Exception e) {
e.printStackTrace();
}
I am new in Java. What else can I try?
You can try this:
Writer wr = new FileWriter("aWrite.txt");
wr.write(String.valueOf(1));
wr.write(String.valueOf(1.5));
wr.write(String.valueOf(2));
wr.flush();
wr.close();
Or this approach which is mainly better for bigger data:
File file = new File("aWrite.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("Write the string to text file");
out.newLine();
I find another way. I hope help...
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args)throws IOException {
double[] doubleNumbers = new double[6];
int[] integerNumbers = new int[6];
int intCount = 0;
int doubleCount = 0;
File numbers = new File("numbers.txt");
FileReader fr = new FileReader(numbers);
LineNumberReader lnreader= new LineNumberReader(fr);
String line = "";
while ((line = lnreader.readLine()) != null) {
var _temp = line.split(" ");
for(int i = 0;i<_temp.length;i++) {
if(_temp[i].indexOf(".") > 0) {
doubleNumbers[doubleCount] = Double.parseDouble(_temp[i]);
++doubleCount;
}else {
integerNumbers[intCount] = Integer.parseInt(_temp[i]);
++intCount;
}
}
}
fr.close();
File doubleFile = new File("double.txt");
FileWriter fw = new FileWriter(doubleFile);
for(int i = 0;i<doubleCount;i++) {
fw.write(doubleNumbers[i]+" ");
if((i +1) % 3 == 0)
fw.write("\n");
}
fw.flush();
fw.close();
File integerFile = new File("integer.txt");
FileWriter fw = new FileWriter(integerFile);
for(int i = 0;i<intCount;i++) {
fw.write(integerNumbers[i]+" ");
if((i +1) % 3 == 0)
fw.write("\n");
}
fw.flush();
fw.close();
System.out.print("Done");
}
}

Saving a 2-dimensional Sting Array in a .txt file and load from it

I want to save a 2-dimensional String Array in a .txt file and load it from it in my app. The Array should be editable and expandable in the app. I am not really experienced with BufferedWriter, BufferedReader, FileInputStream and FileOutputStream and things like this.
I have problems with this code: The BufferedWriter and BufferedReader throws a NullPointerException and I don't know why. Or does everyone know a possibillity to do this with FileInputStream and FileoutputStream?
public String path =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFile";
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(path + "/savedFile.txt");
public static void Save(File file, String[][] list)
{
BufferedWriter writer = null;
StringBuilder builder = new StringBuilder();
try
{
writer = new BufferedWriter(new FileWriter(file));
}
catch (IOException e) {e.printStackTrace();}
try
{
try
{
for(int i = 0; i < list.length; i++)
{
for(int j = 0; j < list[i].length; j++)
{
builder.append(list[i][j]+"");
if(j < list.length - 1)
builder.append(",");
}
builder.append("\n");
}
}
catch (Exception e) {e.printStackTrace();}
}
finally
{
try
{
writer.write(builder.toString());
writer.close();
}
catch (IOException e) {e.printStackTrace();}
}
}
public static String[][] Load(File file)
{
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException e) {e.printStackTrace();}
String test;
String[][] array = new String[4][2]; //the indexs are for a specific example; it should be expandable, but I solve that myself
String line;
int row = 0;
try
{
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
int col = 0;
for (String c : cols) {
array[row][col] = c;
col++;
}
row++;
}
}
catch (IOException e) {e.printStackTrace();}
return array;
}
I think that the problem would be with the scope of variables in multiple braces you've used. try this code:
public static void Save(File file, String[][] list) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < list.length; i++) {
for (int j = 0; j < list[i].length; j++) {
builder.append(list[i][j] + "");
if (j < list.length - 1) {
builder.append(",");
}
}
builder.append("\n");
}
try {
Writer writer = new BufferedWriter(new FileWriter(file));
try {
writer.write(builder.toString());
} finally {
writer.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

how to refresh the content of the jtable if you're using notepad to putting data in the jtable

public void readCar() {
String choice = String.valueOf(car_combo1.getSelectedItem());
int ctr = 0;
String filename = null;
if (choice.equals("STATE-Description")) {
filename = TEXT_CAR1.getText();
ctr = 12;
} else if (choice.equals("DISCAS-Camera")) {
filename = TEXT_CAR2.getText();
ctr = 3;
} else if (choice.equals("DISCAS-CAR(for removal)")) {
filename = TEXT_CAR3.getText();
ctr = 11;
} else if (choice.equals("DISCAS-PAR(for removal)")) {
filename = TEXT_CAR4.getText();
ctr = 9;
} else if (choice.equals("Closing CAS for chg w/ customer initiated")) {
filename = TEXT_CAR5.getText();
ctr = 11;
}
try {
File file = new File(filename);
FileReader fr = new FileReader(file.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
for (int i = 0; i < ctr; i++) {
dataCar[i] = br.readLine();
String[] temp;
temp = dataCar[i].split("\\*");
car_table.setValueAt(temp[0], i, 0);
car_table.setValueAt(temp[1], i, 1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This is the read function
private void car_combo1ActionPerformed(java.awt.event.ActionEvent evt) {
String choice = String.valueOf(car_combo1.getSelectedItem());
JTableHeader th = car_table.getTableHeader();
if (choice.equals("STATE-Description")) {
car_table.getColumnModel().getColumn(0).setHeaderValue("STATE");
car_table.getColumnModel().getColumn(1).setHeaderValue("Description");
String[] change_choice_to = {"-", "1006", "1009", "1011", "1013", "1015", "1017", "1018", "1019", "1020", "1021", "1022", "1023"};
DefaultComboBoxModel model = new DefaultComboBoxModel(change_choice_to);
car_combo2.setModel(model);
DefaultTableModel model2 = (DefaultTableModel) car_table.getModel();
model1.fireTableDataChanged();
readCar();
}
}
table.repaint(); and tableModel.fireTableDataChanged(); doesn't work. I tried both of those function but the jtable wouldn't refresh. The notepad with more lines in it stays in the jTable when a lesser lined notepad is called.
I'm using BufferedReader and FileReader to read it from the notepad.
Is there anyway to refresh the table into its default then show the data from the notepad again? Thank you.
So, the basic idea is either you want to update the existing TableModel or replace it with a new one.
Because the number rows seems to change between requests, replacing the model seems to be the safer bet, for example;
This is taken from you readCar method as it's the important part...
try (BufferedReader br = new BufferedReader(new FileReader(new File(filename)))) {
DefaultTableModel model = new DefaultTableModel(new String[]{"STATE", "Description"}, 0);
for (int i = 0; i < ctr; i++) {
dataCar[i] = br.readLine();
String[] temp = dataCar[i].split("\\*");
model.addRow(temp);
}
car_table.setModel(model);
} catch (IOException e) {
e.printStackTrace();
}
All this does is create a new DefaultTableModel, for each line of the file, adds a row to the model and then applies the model to the table when it's done.
If this fails, either there is something else in your code which isn't working or the file is been read (or saved) properly
Take a look at How to Use Tables and The try-with-resources Statement for more details
public void eraseTableCar(){
for(int i = 0; i<110 ; i++){
car_table.setValueAt(" ",i,0);
car_table.setValueAt(" ",i,1);
}
}
public void readCar() {
String choice = String.valueOf(car_combo1.getSelectedItem());
int ctr = 0;
String filename = null;
if (choice.equals("STATE-Description")) {
filename = TEXT_CAR1.getText();
ctr = 12;
} else if (choice.equals("DISCAS-Camera")) {
filename = TEXT_CAR2.getText();
ctr = 3;
} else if (choice.equals("DISCAS-CAR(for removal)")) {
filename = TEXT_CAR3.getText();
ctr = 11;
} else if (choice.equals("DISCAS-PAR(for removal)")) {
filename = TEXT_CAR4.getText();
ctr = 9;
} else if (choice.equals("Closing CAS for chg w/ customer initiated")) {
filename = TEXT_CAR5.getText();
ctr = 11;
}
eraseTableCar();
try {
File file = new File(filename);
FileReader fr = new FileReader(file.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
for (int i = 0; i < ctr; i++) {
dataCar[i] = br.readLine();
String[] temp;
temp = dataCar[i].split("\\*");
car_table.setValueAt(temp[0], i, 0);
car_table.setValueAt(temp[1], i, 1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This code works although I don't know if it's a good practice in coding

replace random number of characters at random position with wildcard

I am trying to create a program which would replace random number of characters at random position with "*". Star is letter used in main program and it is replaced with "." a wildcard to matches any possible result.
So far I manage to create the code you see bellow. It replaces exactly 1 character of specific word.
Any help from here on now would be much appreciated.
EXAMPLE:
Input word: MOUSE
RANDOM GENERATOR for how much characters to replace: 3
RANDOM GENERATOR at which places to replace: 1, 3, 5
RESULT: *O*S*
public class random_2 {
public static void main(String[] args) {
String test;
int dolzina = 0;
String outputFile = "random_2.txt";
ArrayList<String> list = new ArrayList();
try {
File file = new File("random1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
list.add(vrstica);
// dolzina=list.size();
// System.out.println(dolzina);
}
FileWriter fileWriter = new FileWriter(outputFile);
PrintWriter out = new PrintWriter(fileWriter);
for (int idx = 0; idx <= list.size(); ++idx) {
test=list.get(idx);
dolzina=test.length();
Random rGenerator = new Random();
for (int i = 0; i<= dolzina; ++i) {
int randomInt = rGenerator.nextInt(dolzina);
StringBuilder beseda = new StringBuilder(test);
beseda.setCharAt(randomInt, '*');
System.out.println(beseda);
dolzina=0;
}}
System.out.println("Done.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Modified your code and its working:
try {
File file = new File("random1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica = bufferedReader.readLine();
while (vrstica != null) {
list.add(vrstica);
vrstica = bufferedReader.readLine();
// dolzina=list.size();
// System.out.println(dolzina);
}
FileWriter fileWriter = new FileWriter(outputFile);
PrintWriter out = new PrintWriter(fileWriter);
for (int idx = 0; idx < list.size(); ++idx) {
test = list.get(idx);
dolzina = test.length();
Random rGenerator = new Random();
StringBuilder beseda = new StringBuilder(test);
for (int i = 0; i < dolzina; ++i) {
int randomInt = rGenerator.nextInt(dolzina);
beseda.setCharAt(randomInt, '*');
System.out.println(beseda);
}
out.print(beseda);
out.close();
}
you can try something like this:
String mask(String s, int charsToMask){
if(s.length() < charsToMask) throw new IllegalArgumentException();
List<Integer> shuffle = new ArrayList<>(s.length())
for (int i = 0; i < s.length(); i++) {
shuffle.add(i, i);
}
Collections.shuffle(shuffle);
StringBuilder sb = new StringBuilder(s)
for (int i = 0; i < charsToMask; i++) {
sb.setCharAt(shuffle.get(i).intValue(), (char)'*')
}
return sb.toString()
}
print mask("MOUSE", 3)

how to add 2lac line in txt file by java in minimum time?

I am trying to add almost 2lac lines in particular txt file(actually conf file) by java program. But it takes almost 112 min when number is only 189000!
I write following code for that
import java.io.*;
public class Fileshandling_example {
static long s1;
static long e1;
static long e2;
static Fileshandling_example fhe= new Fileshandling_example();
public static void main(String args[]) {
try {
s1 = System.nanoTime();
File file1 = new File("\example\mandar.txt");
LineNumberReader lnr1 = new LineNumberReader(new FileReader(file1));
BufferedReader br1 = new BufferedReader(new FileReader(file1));
lnr1.skip(Long.MAX_VALUE);
int a = 1;
StringBuffer sb1 = new StringBuffer("[stations]");
String sCurrentline1 = br1.readLine();
while ((sCurrentline1 = br1.readLine()) != null) {
a++;
if (sCurrentline1.contentEquals(sb1) == true) {
int count = a;
int arraycount = 100000;
for(int i =0; i< (arraycount+1); i++){
if(0 == (i%10000)){
e2 = System.nanoTime();
System.out.println("Time = "+(e2-s1));
}
String abc ="extern => 00"+(1000 + (arraycount-i))+",1,Wait(0.05)";
fhe.insertintoExtensions(file1, (count+1),abc);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
e1 = System.nanoTime();
System.out.println("Time = "+(e1-s1));
}
public void insertintoExtensions(File inFile1, int lineno, String s1)throws Exception {
File outFile1 = new File("\example\111.tmp");
FileInputStream fis = new FileInputStream(inFile1);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream(outFile1);
PrintWriter out = new PrintWriter(fos);
String thisLine = "";
int i =1;
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(s1);
out.println(thisLine);
i++;
}
out.flush();
out.close();
in.close();
inFile1.delete();
outFile1.renameTo(inFile1);
}
}
Can any one help me where i get wrong?
I asked similar question coderanch but here i get clue very fast so i ask here also.
Sorry for that (cross forum asking).
Thanks.
You are loop 100,000 times for every '[stations]' found on "\example\mandar.txt":
if (sCurrentline1.contentEquals(sb1) == true) {
int count = a;
int arraycount = 100000;
for(int i =0; i< (arraycount+1); i++){
and call fhe.insertintoExtensions which loops "\example\mandar.txt" again to copy or the content of the line or the content of s1 parameter until the actual line number is reached:
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(s1);
out.println(thisLine);
i++;
}
Try to improve you code and use BufferedWriter instead of PrintWriter.

Categories