How to open java,python,other files in a JEditorPane - java

So I was wondering how I can actively change the color of keywords in the java text pane. I understand a document listener is will have to be used, but at the moment it doesn't seem to be working, in fact putting it in the document listener leads to me not being able to properly open a file or color at all. So how can I actively call a method that changes color of keywords in java. This is the code that will search for keywords and it works when I open files, just not actively.
public void findKeyWords(String directory) throws FileNotFoundException
{
final StyleContext cont = StyleContext.getDefaultStyleContext();
final AttributeSet jKeyWord = cont.addAttribute(cont.getEmptySet(),
StyleConstants.Foreground,Color.RED);
final AttributeSet jOperator = cont.addAttribute(cont.getEmptySet(),
StyleConstants.Foreground,Color.MAGENTA);
final AttributeSet jtypes = cont.addAttribute(cont.getEmptySet(),
StyleConstants.Foreground,Color.CYAN);
ArrayList<String> words = loadKeyWords(directory);
for (String line : words)
{
searchJava(line,jKeyWord);
}
ArrayList<String> operators = loadOperators(directory);
for (String line : operators)
{
searchJava(line, jOperator);
}
ArrayList<String> types1 = loadTypes(directory);
for (String line : types1)
{
searchJava(line, jtypes);
}
}
private ArrayList<String> loadKeyWords(String directory) throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
final String dir = System.getProperty("user.dir");
File file = new File(dir + "/" + directory + "/keywords.txt");
Scanner scan = new Scanner(file);
while(scan.hasNext())
{
javaWords.add(scan.next() + " ");
}
scan.close();
return javaWords;
}
private ArrayList<String> loadOperators(String directory) throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
final String dir = System.getProperty("user.dir");
File file = new File(dir + "/" + directory + "/operators.txt");
Scanner scan = new Scanner(file);
while(scan.hasNext())
{
javaWords.add(scan.next());
}
scan.close();
return javaWords;
}
private ArrayList<String> loadTypes(String directory) throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
final String dir = System.getProperty("user.dir");
File file = new File(dir + "/" + directory + "/types.txt");
Scanner scan = new Scanner(file);
while(scan.hasNext())
{
javaWords.add(" " + scan.next());
}
scan.close();
return javaWords;
}
public void searchJava(String wordToSearch, AttributeSet javaAttr)
{
final AttributeSet attr = javaAttr;
Document text = textArea.getDocument();
int m;
int t;
int total = 0;
for (String line : textArea.getText().split("\n"))
{
m = line.indexOf(wordToSearch);
if(m == -1)
{
if(isUnix())
{
total += line.length() + 1;
}
else if(isWindows())
{
total += line.length();
}
else if(isMac())
{
total += line.length() + 1;
}
else
{
total += line.length() + 1;
}
continue;
}
try{
text.remove(total + m, wordToSearch.length());
text.insertString(total + m, wordToSearch, attr);
}catch(BadLocationException ex)
{}
while(true)
{
m = line.indexOf(wordToSearch, m + 1 );
if (m == -1)
{
break;
}
try
{
text.remove(total + m, wordToSearch.length());
text.insertString(total + m, wordToSearch, attr);
}catch(BadLocationException e)
{
}
}
if(isUnix())
{
total += line.length() + 1;
}
else if(isWindows())
{
total += line.length();
}
else if(isMac())
{
total += line.length() + 1;
}
else
{
JOptionPane.showMessageDialog(null, "Eric You Troll" );
total += line.length() + 1;
}
}
}

Related

Problem with reading textfiles with scanner in Java and ArrayLists

I'm having a problem where I read a textfile named "songs.txt" with Scanner in a function called loadFiles() which every line is:
Music ID # Song Name # Release Date
And with this I create a Song object, and then store said object in a ArrayList. After reading the file, I clone this ArrayList so I can return a ArrayList with the songs read and clear the first ArrayList to prevent the cases where for exemple:
(PS: I use the ArrayLists as global variables)
songs.txt has this structure:
1oYYd2gnWZYrt89EBXdFiO#Message In A Bottle#1979
7zxc7dmd82nd92nskDInds#Sweet Child of Mine#1980
And the loadFiles() is called 2 times, the ArrayList would have a size of 4 instead of 2 as it should be. So that's why after songs.txt is read I copy the arrayList and then clear the first ArrayList that way the ArrayList that's returned only has the size of 2.
This is my code:
package pt.ulusofona.aed.deisiRockstar2021;
import java.io.IOException;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Main {
public static ArrayList < Song > teste6 = new ArrayList < > ();
public static ArrayList < Song > getSongsArray = new ArrayList < > ();
public static ArrayList < Artista > testeSongArtists = new ArrayList < > ();
public static ParseInfo parseInfoSongsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsArtistsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsDetailsTxT = new ParseInfo(0, 0);
public static void main(String[] args) throws IOException {
ArrayList < Song > teste7 = new ArrayList < Song > ();
loadFiles();
loadFiles();
teste7 = getSongs();
ParseInfo teste8 = getParseInfo("songs.txt");
System.out.println("\n----------------------TESTE DO MAIN----------------------");
System.out.println(teste7.toString());
System.out.println(teste8.toString());
System.out.println(getSongsArray.size());
}
public static void loadFiles() throws IOException {
//Aqui lê-se o ficheiro songs.txt
System.out.println("----------------------LEITURA DO FICHEIRO songs.txt------------");
String nomeFicheiro = "songs.txt";
try {
File ficheiro = new File(nomeFicheiro);
FileInputStream fis = new FileInputStream(ficheiro);
Scanner leitorFicheiro = new Scanner(fis);
while (leitorFicheiro.hasNextLine()) {
String linha = leitorFicheiro.nextLine();
String dados[] = linha.split("#");
if (dados.length != 3) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[2].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
//Meter para ignorar a acabar com espaço
parseInfoSongsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String nome = dados[1];
int anoLancamento = Integer.parseInt(dados[2]);
Song song = new Song(idTemaMusical, nome, null, anoLancamento, 0, false, 0, 0, 0, 0);
teste6.add(song);
}
leitorFicheiro.close();
getSongsArray = (ArrayList < Song > ) teste6.clone();
teste6.clear();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro + " nao foi encontrado.";
System.out.println(mensagem);
}
System.out.println(teste6.toString());
System.out.println("Ok: " + parseInfoSongsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_artists.txt------------");
//Aqui é lido o ficheiro song_artists.txt, mas falta ver se é preciso separar vários artistas com o mesmo ID para posições diferentes no ArrayList
String nomeFicheiro2 = "song_artists.txt";
try {
File song_artists = new File(nomeFicheiro2);
FileInputStream fis2 = new FileInputStream(song_artists);
Scanner leitorFicheiro2 = new Scanner(fis2);
while (leitorFicheiro2.hasNextLine()) {
String linha = leitorFicheiro2.nextLine();
String dados[] = linha.split("#");
if (dados.length != 2) {
parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsArtistsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String artista = dados[1];
Artista artista2 = new Artista(idTemaMusical, artista);
testeSongArtists.add(artista2);
}
leitorFicheiro2.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro2 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println(testeSongArtists.toString());
System.out.println("Ok: " + parseInfoSongsArtistsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_details.txt------------");
//Aqui lê-se o ficheiro song_details.txt
boolean letra = false;
ArrayList < Song > testeSongDetails = new ArrayList < Song > ();
String nomeFicheiro3 = "song_details.txt";
try {
File song_details = new File(nomeFicheiro3);
FileInputStream fis3 = new FileInputStream(song_details);
Scanner leitorFicheiro3 = new Scanner(fis3);
while (leitorFicheiro3.hasNextLine()) {
String linha = leitorFicheiro3.nextLine();
String dados[] = linha.split("#");
if (dados.length != 7) {
parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[3].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[4].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[5].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[6].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsDetailsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
//System.out.println(idTemaMusical);
int duracao = Integer.parseInt(dados[1]);
//System.out.println(duracao);
int letraExplicita = Integer.parseInt(dados[2]);
//System.out.println(letraExplicita);
if (letraExplicita == 0) {
letra = false;
} else {
letra = true;
}
//System.out.println(letra);
int populariedade = Integer.parseInt(dados[3]);
//System.out.println(populariedade);
double dancabilidade = Double.parseDouble(dados[4]);
//System.out.println(dancabilidade);
double vivacidade = Double.parseDouble(dados[5]);
//System.out.println(vivacidade);
double volumeMedio = Double.parseDouble(dados[6]);
//System.out.println(volumeMedio);
Song song = new Song(idTemaMusical, null, null, 0, duracao, letra, populariedade, dancabilidade, vivacidade, volumeMedio);
testeSongDetails.add(song);
}
leitorFicheiro3.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro3 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println("Ok: " + parseInfoSongsDetailsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED);
}
public static ArrayList < Song > getSongs() {
return getSongsArray;
}
public static ParseInfo getParseInfo(String fileName) {
if (fileName == "songs.txt") {
return parseInfoSongsTxT;
}
if (fileName == "song_artists.txt") {
return parseInfoSongsArtistsTxT;
}
if (fileName == "song_details.txt") {
return parseInfoSongsDetailsTxT;
}
return null;
}
}
The problem is that when I made a test to check the function where the ArrayList is returned to see the size of the ArrayList it always comes as 0.
I think it's because only the function the returns the ArrayList is tested so loadFiles() isn't executed so the ArrayListo never gets cloned and that makes the ArrayList that is returned stay the same.
I thought about calling loadFiles() inside getSongs() and that way I would guarantee that the ArrayList is cloned but that would make getSongs use "throws IOException" and since I have to respect the school's project guide and getSongs doesn't include "throws IOException" i can't put it there.
But the more I think about it, that doesn't even make sense because how can they test it with a file of their own and loadFiles() isn't executed?
I'm out of ideas how to solve this problem, any help is welcome thank you.

TreeMap with (String,ArrayList<String,Int>)

I am trying to read an input file. Each value of the input file is inserted into the TreeMap as
If word is not existing: Insert the word to the treemap and associate the word with an ArrayList(docId, Count).
If the Word is present in the TreeMap, then check if the current DocID matches within the ArrayList and then increase the count.
THe
For the ArrayList, I created another class as below:
public class CountPerDocument
{
private final String documentId;
private final int count;
CountPerDocument(String documentId, int count)
{
this.documentId = documentId;
this.count = count;
}
public String getDocumentId()
{
return this.documentId;
}
public int getCount()
{
return this.count;
}
}
After that, I am trying to print the TreeMap into a text file as <DocID - Count>
Not sure what I am doing wrong here, but the output I get is as follows:
The Stem is todai:[CountPerDocument#5caf905d, CountPerDocument#27716f4, CountPerDocument#8efb846, CountPerDocument#2a84aee7, CountPerDocument#a09ee92, CountPerDocument#30f39991]
Wondering if anyone can guide me what i am doing wrong and if my method isn't correct what am i supposed to do?
public class StemTreeMap
{
private static final String r1 = "\\$DOC";
private static final String r2 = "\\$TITLE";
private static final String r3 = "\\$TEXT";
private static Pattern p1,p2,p3;
private static Matcher m1,m2,m3;
public static void main(String[] args)
{
BufferedReader rd,rd1;
String docid = null;
String id;
int tf = 0;
//CountPerDocument cp = new CountPerDocument(docid, count);
List<CountPerDocument> ls = new ArrayList<>();
Map<String,List<CountPerDocument>> mp = new TreeMap<>();
try
{
rd = new BufferedReader(new FileReader(args[0]));
rd1= new BufferedReader(new FileReader(args[0]));
int docCount = 0;
String line = rd.readLine();
p1 = Pattern.compile(r1);
p2 = Pattern.compile(r2);
p3 = Pattern.compile(r3);
while(line != null)
{
m1 = p1.matcher(line);
m2 = p2.matcher(line);
m3 = p3.matcher(line);
if(m1.find())
{
docid = line.substring(5, line.length());
docCount++;
//System.out.println("The Document ID is :");
//System.out.println(docid);
line = rd.readLine();
}
if(m2.find()||m3.find())
{
line = rd.readLine();
}
else
{
if(!(mp.containsKey(line))) // if the stem is not on the TreeMap
{
//System.out.println("The stem is not present in the tree");
tf = 1;
ls.add(new CountPerDocument(docid,tf));
mp.put(line, ls);
line = rd.readLine();
}
else
{
if(ls.indexOf(docid) > 0) //if its last entry matches the current document number
{
//System.out.println("The Stem is present for the same docid so incrementing docid");
tf = tf+1;
ls.add(new CountPerDocument(docid,tf));
line = rd.readLine();
}
else
{
//System.out.println("Stem is present but not the same docid so inserting new docid");
tf = 1;
ls.add(new CountPerDocument(docid,tf)); //set did to the current document number and tf to 1
line = rd.readLine();
}
}
}
}
rd.close();
System.out.println("The Number of Documents in the file is:"+ docCount);
//Write to an output file
String l = rd1.readLine();
File f = new File("dictionary.txt");
if (f.createNewFile())
{
System.out.println("File created: " + f.getName());
}
else
{
System.out.println("File already exists.");
Path path = Paths.get("dictionary.txt");
Files.deleteIfExists(path);
System.out.println("Deleted Existing File:: Creating New File");
f.createNewFile();
}
FileWriter fw = new FileWriter("dictionary.txt");
fw.write("The Total Number of Stems: " + mp.size() +"\n");
fw.close();
System.out.println("The Stem is todai:" + mp.get("todai"));
}catch(IOException e)
{
e.printStackTrace();
}
}
}
You didn't define the function String toString() in your class CountPerDocument. So, when you try to print a CountPerDocument variable, the default printed value is CountPerDocument#hashcode.
To decide how to represent a CountPerDocument variable in your code, add in your class the next function:
#Override
public String toString() {
return "<" + this.getDocumentId() + ", " + this.getCount() + ">";
}
Try to override toString method in CountPerDocument. Something like this:
public class CountPerDocument
{
private final String documentId;
private final int count;
CountPerDocument(String documentId, int count)
{
this.documentId = documentId;
this.count = count;
}
public String getDocumentId()
{
return this.documentId;
}
public int getCount()
{
return this.count;
}
#Override
public String toString() {
return documentId + "-" + count;
}
}

Using scanner to read file and group data

I'm using scanner to read file and group data , ive done some work but facing problem when im tring to deal with
The data sets is this.
You can see a example here, that explain everything.
What i ve done is this :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class TextScanner {
// static File f = new File("nrp1.txt");
public static void main(String[] args) throws FileNotFoundException {
TextScanner ts = new TextScanner();
ts.readfile();
}
public void readfile() throws FileNotFoundException {
FileInputStream fis = new FileInputStream("nrp1.txt");
Scanner scanner = new Scanner(fis);
int lineCount = 0;
String firstline = scanner.nextLine();
String secondline = scanner.nextLine();
String thirdline = scanner.nextLine();
String fourthline = scanner.nextLine();
String fifthline = scanner.nextLine();
String sixthline = scanner.nextLine();
String seventhline = scanner.nextLine();
String eighththline = scanner.nextLine();
List<Integer> intArrRIDA = new ArrayList<Integer>();
List<Integer> intArrRIDB = new ArrayList<Integer>();
int[] intRIDA = new int[Integer.parseInt(eighththline)];
int[] intRIDB = new int[Integer.parseInt(eighththline)];
List<Integer> intArrPOC = new ArrayList<Integer>();
List<Integer> intArrNORBC = new ArrayList<Integer>();
List<Integer> intArrRL = new ArrayList<Integer>();
String NoC="";
// COR arrays
thirdline.trim();
String[] CoR1 = thirdline.split(" ");
int[] intCoR1 = new int[CoR1.length];
for (int i = 0; i < intCoR1.length; i++) {
intCoR1[i] = Integer.parseInt(CoR1[i]);
}
fifthline.trim();
String[] CoR2 = fifthline.split(" ");
int[] intCoR2 = new int[CoR2.length];
for (int i = 0; i < intCoR2.length; i++) {
intCoR2[i] = Integer.parseInt(CoR2[i]);
}
seventhline.trim();
String[] CoR3 = seventhline.split(" ");
int[] intCoR3 = new int[CoR3.length];
for (int i = 0; i < intCoR3.length; i++) {
intCoR3[i] = Integer.parseInt(CoR3[i]);
}
while (scanner.hasNextLine()) {
lineCount++;
String line = scanner.nextLine().trim();
if (lineCount >= 1 && lineCount <= Integer.parseInt(eighththline)) {
// System.out.println("line: " + line);
String[] RID = line.split(" ");
for (int i = 0; i < 1; i++) {
intArrRIDA.add(Integer.parseInt(RID[0]));
intArrRIDB.add(Integer.parseInt(RID[1]));
// intRIDA[i] = Integer.parseInt(RID[0]);
// intRIDB[i] = Integer.parseInt(RID[1]);
// System.out.println("Id of RequirementA : " + intRIDA[i]);
// System.out.println("Id of RequirementB : " + intRIDB[i]);
}
}
if (lineCount == Integer.parseInt(eighththline)) {
NoC = scanner.nextLine();
}
//System.out.println("Number of Customer : " + NoC);
if (lineCount > Integer.parseInt(eighththline)) {
// System.out.println("line: " + line);
String[] Customers = line.split(" ");
System.out.println("Details of Customer : " +Arrays.toString(Customers) );
intArrPOC.add(Integer.parseInt(Customers[0]));
intArrNORBC.add(Integer.parseInt(Customers[1]));
for (int i = 0; i < 6; i++) {
intArrRL.add(Integer.parseInt(Customers[2]));
if (Customers[3] != null) {
intArrRL.add(Integer.parseInt(Customers[3]));
}
else if (Customers[4] != null) {
intArrRL.add(Integer.parseInt(Customers[4]));
}
else if (Customers[5] != null) {
intArrRL.add(Integer.parseInt(Customers[5]));
}
else if (Customers[6] != null) {
intArrRL.add(Integer.parseInt(Customers[6]));
}
else
continue;
}
}
}
System.out.println("Level of requirements, t: " + firstline);
System.out.println("Number of requirements in Level 1: " + secondline);
System.out.println("Costs of requirements in Level 1 : "
+ Arrays.toString(intCoR1));
System.out.println("Number of requirements in Level 2: " + fourthline);
System.out.println("Costs of requirements in Level 2 : "
+ Arrays.toString(intCoR2));
System.out.println("Number of requirements in Level 3: " + sixthline);
System.out.println("Costs of requirements in Level 3 : "
+ Arrays.toString(intCoR3));
System.out.println("Number of dependencies: " + eighththline);
// System.out.println("Id of RequirementA : " +
// Arrays.toString(intRIDA));
// System.out.println("Id of RequirementB : " +
// Arrays.toString(intRIDB));
System.out.println("Id of RequirementA : " + intArrRIDA);
System.out.println("Id of RequirementB : " + intArrRIDB);
System.out.println("Number of Customer : " + NoC);
System.out.println("Profit of Customer : " + intArrPOC);
System.out.println("Number of requests by Customer: " + intArrNORBC);
System.out.println("Requirements List : " + intArrRL);
}
private boolean isNumeric(String number) {
try {
Integer.parseInt(number);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
But as you can see :
for (int i = 0; i < 6; i++) {
intArrRL.add(Integer.parseInt(Customers[2]));
if (Customers[3] != null) {
intArrRL.add(Integer.parseInt(Customers[3]));
}
else if (Customers[4] != null) {
intArrRL.add(Integer.parseInt(Customers[4]));
}
else if (Customers[5] != null) {
intArrRL.add(Integer.parseInt(Customers[5]));
}
else if (Customers[6] != null) {
intArrRL.add(Integer.parseInt(Customers[6]));
}
else
continue;
}
This part is not correct ,and i need them to linked with Profit of Customer and Number of requests by Customer and when i implement further stuffs, i may able to find the corresponding Requirements List and the number of request by Profit of Customer...
I haven't started doing this method yet but that would be great if you can help me with this as well!
Thanks!

How to convert multipage PDF to multipage TIFF

I am using Ghost4j to convert multipage PDFs to multipage TIFF images. I haven't found an example of how this is done.
Using below code I'm able to convert the multipage PDF to images but how do I create a single multipage TIFF image out of it?
PDFDocument lDocument = new PDFDocument();
lDocument.load(filePath);
// create renderer
SimpleRenderer lRenderer = new SimpleRenderer();
// set resolution (in DPI)
lRenderer.setResolution(300);
// render as images
List<Image> lImages = lRenderer.render(lDocument);
Iterator<Image> lImageIterator = lImages.iterator();
//how to convert the images to a single TIFF image?
While this is not exactly what you are doing I did something similar. I combined multiple images in one directory into a tiff file with separate pages. Take a look at this code and see if you can pick out what you need. Also you will need external jars/libraries for this to work they can be downloaded just google them. I hope this helps you.
public class CombineImages {
private static String directory = null;
private static String combinedImageLocation = null;
private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static int folderCount = 0;
private static int totalFolderCount = 0;
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the directory path that contains the images: ");
directory = scanner.nextLine(); //initialize directory
System.out.println("Please enter a location for the new combined images to be placed: ");
combinedImageLocation = scanner.nextLine(); //initialize directory
if(!(combinedImageLocation.charAt((combinedImageLocation.length() - 1)) == '\\'))
{
combinedImageLocation += "\\";
}
if(!(directory.charAt((directory.length() - 1)) == '\\'))
{
directory += "\\";
}
scanner.close();
//directory = "C:\\Users\\sorensenb\\Desktop\\CombinePhotos\\";
//combinedImageLocation = "C:\\Users\\sorensenb\\Desktop\\NewImages\\";
File filesDirectory;
filesDirectory = new File(directory);
File[] files; //holds files in given directory
if(filesDirectory.exists())
{
files = filesDirectory.listFiles();
totalFolderCount = files.length;
folderCount = 0;
if(files != null && (files.length > 0))
{
System.out.println("Start Combining Files...");
System.out.println("Start Time: " + dateFormat.format(new Date()));
combineImages(files);
System.out.println("Finished Combining Files.");
System.out.println("Finish Time: " + dateFormat.format(new Date()));
}
}
else
{
System.out.println("Directory does not exist!");
System.exit(1);
}
}
public static void combineImages(File[] files)
{
int fileCounter = 1;
ArrayList<String> allFiles = new ArrayList<String>();
String folderBase = "";
String parentFolder = "";
String currentFileName = "";
String previousFileName = "";
File previousFile = null;
int counter = 0;
for(File file:files)
{
if(file.isDirectory())
{
folderCount++;
System.out.println("Folder " + folderCount + " out of " + totalFolderCount + " folders.");
combineImages(file.listFiles());
}
else
{
try {
folderBase = file.getParentFile().getCanonicalPath();
parentFolder = file.getParentFile().getName();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(counter == 0)
{
allFiles.add(file.getName().substring(0, file.getName().indexOf('.')));
}
else
{
currentFileName = file.getName();
previousFileName = previousFile.getName();
currentFileName = currentFileName.substring(0, currentFileName.indexOf('.'));
previousFileName = previousFileName.substring(0, previousFileName.indexOf('.'));
if(!currentFileName.equalsIgnoreCase(previousFileName))
{
allFiles.add(currentFileName);
}
}
}
previousFile = file;
counter++;
}
System.out.println("Total Files to be Combined: " + allFiles.size());
for(String currentFile:allFiles)
{
System.out.println("File " + fileCounter + " out of " + allFiles.size() + " CurrentFile: " + currentFile);
try {
createNewImage(currentFile, files, folderBase, parentFolder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileCounter++;
}
}
***public static void createNewImage(String currentFile, File[] files, String folderBase, String parentFolder) throws IOException
{
//BufferedImage image;
int totalHeight = 0;
int maxWidth = 0;
int currentHeight = 0;
ArrayList<String> allFiles = new ArrayList<String>();
for(File file:files)
{
if((file.getName().substring(0, file.getName().indexOf('.'))).equalsIgnoreCase(currentFile))
{
allFiles.add(file.getName());
}
}
allFiles = sortFiles(allFiles);
BufferedImage image[] = new BufferedImage[allFiles.size()];
SeekableStream ss = null;
PlanarImage op = null;
for (int i = 0; i < allFiles.size(); i++) {
ss = new FileSeekableStream(folderBase + "\\" + allFiles.get(i));
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
op = new NullOpImage(decoder.decodeAsRenderedImage(0),
null, null, OpImage.OP_IO_BOUND);
image[i] = op.getAsBufferedImage();
}
op.dispose();
ss.close();
/*BufferedImage convertImage;
for(int i = 0; i < image.length; i++)
{
convertImage = new BufferedImage(image[i].getWidth(),image[i].getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = convertImage.getGraphics();
g.drawImage(convertImage, 0, 0, null);
g.dispose();
image[i] = convertImage;
}*/
File folderExists = new File(combinedImageLocation);
if(!folderExists.exists())
{
folderExists.mkdirs();
}
TIFFEncodeParam params = new TIFFEncodeParam();
params.setCompression(TIFFEncodeParam.COMPRESSION_GROUP3_1D);
int changeName = 1;
String tempCurrentFile = currentFile;
while((new File(combinedImageLocation + tempCurrentFile + "Combined.tif").exists()))
{
tempCurrentFile = currentFile;
tempCurrentFile += ("(" + changeName + ")");
changeName++;
}
currentFile = tempCurrentFile;
OutputStream out = new FileOutputStream(combinedImageLocation + currentFile + "Combined" + ".tif");
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
Vector vector = new Vector();
for (int i = 1; i < allFiles.size(); i++) {
vector.add(image[i]);
}
params.setExtraImages(vector.iterator());
encoder.encode(image[0]);
for(int i = 0; i < image.length; i++)
{
image[i].flush();
}
out.close();
System.gc();
/*for(String file:allFiles)
{
image = ImageIO.read(new File(folderBase, file));
int w = image.getWidth();
int h = image.getHeight();
totalHeight += h;
if(w > maxWidth)
{
maxWidth = w;
}
image.flush();
}
BufferedImage combined = new BufferedImage((maxWidth), (totalHeight), BufferedImage.TYPE_BYTE_GRAY);
for(String file:allFiles)
{
Graphics g = combined.getGraphics();
image = ImageIO.read(new File(folderBase, file));
int h = image.getHeight();
g.drawImage(image, 0, currentHeight, null);
currentHeight += h;
image.flush();
g.dispose();
}
File folderExists = new File(combinedImageLocation + parentFolder + "\\");
if(!folderExists.exists())
{
folderExists.mkdirs();
}
ImageIO.write(combined, "TIFF", new File(combinedImageLocation, (parentFolder + "\\" + currentFile + "Combined.tif")));
combined.flush();
System.gc();*/
}***
public static ArrayList<String> sortFiles(ArrayList<String> allFiles)
{
ArrayList<String> sortedFiles = new ArrayList<String>();
ArrayList<String> numbers = new ArrayList<String>();
ArrayList<String> letters = new ArrayList<String>();
for(String currentFile:allFiles)
{
try
{
Integer.parseInt(currentFile.substring((currentFile.indexOf('.') + 1)));
numbers.add(currentFile);
}catch(Exception e)
{
letters.add(currentFile);
}
}
//String[] numbersArray = new String[numbers.size()];
//String[] lettersArray = new String[letters.size()];
for(int i = 0; i < numbers.size(); i++)
{
sortedFiles.add(numbers.get(i));
}
for(int i = 0; i < letters.size(); i++)
{
sortedFiles.add(letters.get(i));
}
return sortedFiles;
}
}

The program throws NullPointerException [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Not sure why it gives me the NullPointerException. Please help.
I am pretty sure all the arrays are full, and i restricted all the loops not to go passed empty spaces.
import java.util.;
import java.io.;
public class TextAnalysis {
public static void main (String [] args) throws IOException {
String fileName = args[0];
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int MAX_WORDS = 10000;
String[] words = new String[MAX_WORDS];
int unique = 0;
System.out.println("TEXT FILE STATISTICS");
System.out.println("--------------------");
System.out.println("Length of the longest word: " + longestWord(fileScanner));
read(words, fileName);
System.out.println("Number of words in file wordlist: " + wordList(words));
System.out.println("Number of words in file: " + countWords(fileName) + "\n");
System.out.println("Word-frequency statistics");
lengthFrequency(words);
System.out.println();
System.out.println("Wordlist dump:");
wordFrequency(words,fileName);
}
public static void wordFrequency(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
int [] array = new int [words.length];
while(s.hasNext()) {
String w = s.next();
if(w!=null){
for(int i = 0; i < words.length; i++){
if(w.equals(words[i])){
array[i]++;
}
}
for(int i = 0; i < words.length; i++){
System.out.println(words[i] + ":" + array[i]);
}
}
}
}
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int[10];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(w!=null){
if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}
}
for(int j = 0; j < 10; j++) {
System.out.println("Word-length " + (j+1) + ": " + lengthTimes[j]);
}
}
public static String longestWord (Scanner s) {
String longest = "";
while (s.hasNext()) {
String word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
return (longest.length() + " " + "(\"" + longest + "\")");
}
public static int countWords (String fileName) throws IOException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int count = 0;
while(fileScanner.hasNext()) {
String word = fileScanner.next();
count++;
}
return count;
}
public static void read(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
while (s.hasNext()) {
String word = s.next();
int i;
for ( i=0; i < words.length && words[i] != null; i++ ) {
words[i]=words[i].toLowerCase();
if (words[i].equals(word)) {
break;
}
}
words[i] = word;
}
}
public static int wordList(String[] words) {
int count = 0;
while (words[count] != null) {
count++;
}
return count;
}
}
There are two problems with this code
1.You didn't do null check,although the array contains null values
2.Your array index from 0-8,if you wan't to get element at 9th index it will throw ArrayIndexOutOfBound Exception.
Your code should be like that
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int [9];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w) //This one added for null check
{
/* if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}*/
//Don't need to check like that ...u can do like below
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w)
{
lengthTimes[i] =w.length();
}
}
}
//here we should traverse upto length of the array.
for(int i = 0; i < lengthTimes.length; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]);
}
}
Your String Array String[] words = new String[MAX_WORDS]; is not initialized,you are just declaring it.All its content is null,calling length method in line 31 will give you null pointer exception.
`
Simple mistake. When you declare an array, it is from size 0 to n-1. This array only has indexes from 0 to 8.
int [] lengthTimes = new int [9];
//some code here
lengthTimes[9]++; // <- this is an error (this is line 29)
for(int i = 0; i < 10; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]); // <- same error when i is 9. This is line 37
When you declare:
String[] words = new String[MAX_WORDS];
You're creating an array with MAX_WORDS of nulls, if your input file don't fill them all, you'll get a NullPointerException at what I think is line 37 in your original file:
if(w.length() >= 10) { // if w is null this would throw Npe
To fix it you may use a List instead:
List<String> words = new ArrayList<String>();
...
words.add( aWord );
Or perhaps you can use a Set if you don't want to have repeated words.

Categories

Resources