In my code when I add a project to my library and I want to use it, it has ERROR that says
"TextReader is not public in pack4.TextReader; cannot be accessed from
outside package"
But here is my code in pack4:
package pack4;
public class TextReader {
private String path;
TextReader (String path) {
this.path = path;
}
public String[] readFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader bf = new BufferedReader(fr);
int numberOfLines = numberOfLines();
String[] textData = new String[numberOfLines];
int counter = 0;
for(counter = 0; counter < numberOfLines; counter++) {
textData[counter] = bf.readLine();
}
bf.close();
return textData;
}
public int numberOfLines() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader bf = new BufferedReader(fr);
int lineCounter = 0;
while(bf.readLine() != null) {
lineCounter++;
}
bf.close();
return lineCounter;
}
}
Based on your incomplete description, I'm guessing you should probably add "public" to constructor.
Related
so I'm trying to make a greedy/jewel heist algorithm in java. I saved the numbers and weights for the jewels to a .txt file. My program is correctly reading the .txt file and I've written a program that can successfully read them. these are the numbers from my .txt file
575 - bag limit
125 3000 (weight, value)
50 100
500 6000
25 30
The problem I'm running into is that I'm struggling to add weights and values to the program. ideally the program would read the tuples and assign them keys and values. I tried to use a hashmap and a regular Map but they haven't been working. possibly because they're in the wrong place. I included both attempted maps and have them commented out like in my program. Would love some help on assigning these values so I can move on to the next step. thanks!!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
// import java.util.HashMap;
// import java.util.Map;
public class readstringastext {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new
BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
String weightLimit = Files.readAllLines(Paths.get("test.txt")).get(0);
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
HashMap<String, String> map = new HashMap<String, String>();
//
// for (String string : pairs) {
// String[] keyValue = string.split(" ");
// map.put(keyValue[0], keyValue[1]);
// System.out.println(keyValue);
// };
//final class MyEntry<K, V> implements Map.Entry<K, V> {
// private final K key;
// private V value;
//
// public MyEntry(K key, V value) {
// this.key = key;
// this.value = value;
// }
// #Override
// public K getKey() {
// return key;
// }
//
// #Override
// public V getValue() {
// return value;
// }
//
// #Override
// public V setValue(V value) {
// V old = this.value;
// this.value = value;
// return old;
// }
// Map.Entry<String, Object> entry = new MyEntry <String, Object>(key, value);
// System.out.println(entry.getKey());
// System.out.println(entry.getValue());
}
}
attempt 2
public class readstringastext {
public static HashMap<String, String> map = new HashMap<String, String>();
public static void weightLimit() {
String weightLimit = "";
System.out.println(weightLimit);
// this is to see if the weightLimit is there which it isnt'.
}
public static void main(String[] args){
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
String weightLimit = "";
boolean first = true;
while ((line = bufferedReader.readLine()) != null) {
if (first) {
weightLimit = line;
first = false;
} else {
String[] values = line.split(" ");
map.put(values[0], values[1]);
}
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I see your code and and I see you read two times the file with Files.readAllLines() and standard method. So I suggest you this solution but you can use Files.readAllLines() too.
public class Main {
public static HashMap<String, String> map = new HashMap<String, String>();
private static String weightLimit = "";
public static void main(String[] args){
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
boolean first = true;
while ((line = bufferedReader.readLine()) != null) {
if (first) {
weightLimit = line;
first = false;
} else {
String[] values = line.split(" ");
map.put(values[0], values[1]);
}
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
weightLimit();
}
public static void weightLimit() {
System.out.println(weightLimit);
}
}
I believe you want to pass in the weight/value pair into a map data structure, I modified your code a little below to enable this:
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
String weightLimit = Files.readAllLines(Paths.get("test.txt")).get(0);
int count = 0;
while ((line = bufferedReader.readLine()) != null) {
if (count != 0) { // ignore the first line
String[] splitValue = line.split(" ");
map.put(splitValue[0], splitValue[1]);
}
count++;
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
// for (Map.Entry<String, String> entry : map.entrySet()) {
// System.out.println(entry.getKey());
// System.out.println(entry.getValue());
// }
}
I've compiled and debugged my program, but there is no output. I suspect an issue passing from BufferedReader to the array method, but I'm not good enough with java to know what it is or how to fix it... Please help! :)
public class Viennaproj {
private String[] names;
private int longth;
//private String [] output;
public Viennaproj(int length, String line) throws IOException
{
this.longth = length;
this.names = new String[length];
String file = "names.txt";
processFile("names.txt",5);
sortNames();
}
public void processFile (String file, int x) throws IOException, FileNotFoundException{
BufferedReader reader = null;
try {
//File file = new File("names.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sortNames()
{
int counter = 0;
int[] lengths = new int[longth];
for( String name : names)
{
lengths[counter] = name.length();
counter++;
}
for (int k = 0; k<longth; k++)
{
int counter2 = k+1;
while (lengths[counter2]<lengths[k]){
String temp2;
int temp;
temp = lengths[counter2];
temp2 = names[counter2];
lengths[counter2] = lengths[k];
names[counter2] = names[k];
lengths[k] = temp;
names[k] = temp2;
counter2++;
}
}
}
public String toString()
{
String output = new String();
for(String name: names)
{
output = name + "/n" + output;
}
return output;
}
public static void main(String[] args)
{
String output = new String ();
output= output.toString();
System.out.println(output+"");
}
}
In Java, the public static void main(String[] args) method is the starting point of the application.
You should create an object of Viennaproj in your main method. Looking at your implementation, just creating an object of Viennaproj will fix your code.
Your main method should look like below
public static void main(String[] args) throws IOException
{
Viennaproj viennaproj = new Viennaproj(5, "Sample Line");
String output= viennaproj.toString();
System.out.println(output);
}
And, if you are getting a FileNotFound exception when you execute this, it means that java is not able to find the file.
You must provide complete file path of your file to avoid that issue. (eg: "C:/test/input.txt")
I am new at Java and I am having a little trouble:
I am trying to read chemical samples to represent them at a X-Y graph.
The input file looks like this:
La 0.85678
Ce 0.473
Pr 62.839
...
...
My code stocks only the unpair lines value (0.85678, jumps line, 62.839 at the example), and I cannot realize what is the problem:
public class Procces {
public void readREE() throws IOException {
try{
rEE = new BufferedReader (new FileReader ("src/files/test.txt"));
while ( (currentLine = rEE.readLine() ) != null) {
try {
for (int size = 3;size<10;size++) {
String valueDec=(currentLine.substring(3,size));
//char letra =(char)c;
if ((c=rEE.read()) != -1) {
System.out.println("Max size");
} else
valueD = Double.parseDouble(valueDec);
System.out.println(valueDec);
}
}
catch (Exception excUncertainDecimals) {
}
}
}finally {
try { rEE.close();
} catch (Exception exc) {
}
}
}
String line;
int c = 0;
int counter = 0;
String valueS = null;
String valueSimb = null;
Double valueD = null;
Double logValue = null;
Double YFin=450.0;
String currentLine;
BufferedReader rEE;
}
Thank you in advance, as I can't see why the program jumps the pair lines.
use Java Scanner class.
import java.io.*;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) throws IOException {
try (Scanner s = new Scanner(new BufferedReader(new FileReader("file.txt"))){
while (s.hasNext()) {
System.out.println(s.next());
}
}
}
}
Please have a look at Scanner.
In general is Java a well established language and in most cases you do not have to re-implemented "common" (e.g. reading custom text files) stuff on a low level way.
I get it. Thank you.
Here the code:
import java.io.*
import java.util.Scanner;
public class Process implements Samples{
public void readREE() throws IOException {
try
(Scanner rEE = new Scanner(new BufferedReader(new FileReader("src/files/test.txt")))){
while (rEE.hasNext()) {
element = rEE.next();
if (element.equals("La")) {
String elementValue = rEE.next();
Double value = Double.parseDouble(elementValue);
Double valueChond = 0.237;
Double valueNorm= value/valueChond;
Double logValue = (Math.log(valueNorm)/Math.log(10));
Double yLog = yOrd - logValue*133.33333333;
Sample NormedSampleLa=new Sample("La",yLog);
sampleREE.add(NormedSampleLa);
}
}
} finally {
}
}
public String LaS, CeS, PrS, NdS, PmS, SmS, EuS, GdS, TbS, DyS, HoS, ErS, TmS, YbS, LuS;
public String element, elementValue;
public Double yOrd=450.0;
}
I am trying to do external merge sort. Method: opening all the files in the folder 'output' and getting 1st line and sorting it, and writing it in the 'final' file and then getting the 2nd line of that file and repeating. I get an StackOverflowError. Here my file size is greater then memory.
public class mergefile6 {
public static ArrayList<String> al = new ArrayList<String>();
static HashMap hm = new HashMap();
public static String line;
public static String[][] filepoint = new String[100][2];
public static int fileline=1;
public static int i=0;
public static void main(String[] args) throws Exception{
fileread();
}
public static void fileread() throws Exception{
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
File folder = new File("./output/");
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
int lineCount = 0;
while ((line = bufferedReader.readLine())!=null) {
lineCount++;
if (1 == lineCount) {
hm.put(line,file);
al.add(line);
filepoint[i][0]=file.toString();
filepoint[i][1]=Integer.toString(fileline);
++i;
}
}
}
}
if (null != fileReader){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != bufferedReader){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Sorting(al);
test(al);
} catch (Exception e) {
} finally {
}
}
public static void Sorting(ArrayList<String> al)throws Exception{
int length = al.size();
ArrayList<String> tmp = new ArrayList<String>(al);
mergeSort(al, tmp, 0, al.size() - 1);
}
private static void mergeSort(ArrayList<String> al, ArrayList<String> tmp, int left, int right){
//sort code
}
public static void test(ArrayList<String> al) throws Exception{
BufferedWriter bw = null;
FileWriter fw = null;
fw = new FileWriter("final",true);
bw = new BufferedWriter(fw);
bw.write(al.get(0)+" \n");
//bw.flush();
bw.close();
fw.close();
String filename = hm.get(al.get(0)).toString();
hm.remove(al.get(0));
al.remove(0);
fileforward(filename,al);
}
public static void fileforward(String filename,ArrayList<String> al) throws Exception{
long list;
FileReader fr = null;
BufferedReader br = null;
fr = new FileReader(filename);
br = new BufferedReader(fr);
for(int j=0;j<i;++j){
if(filepoint[j][0] == filename){
fileline = Integer.parseInt(filepoint[j][1]);
list = br.skip(99*fileline);
if((line = br.readLine())!=null){
hm.put(line,filename);
al.add(line);
++fileline;
filepoint[j][1]=Integer.toString(fileline);
br.close(); fr.close();
}else{}
}
}
if(al.size()==3){
Sorting(al);
test(al); }
}
}
What may be causing this error to come?
It might be an overflow caused by the mutual calls between fileforward() and test(). I don't know try debugging the ArrayList's size with logs or prints. If it's always equal to 3 that's the problem.
I delete some lines from an text file that works fine but I have an problem with blank lines.
Those still inside the .txt file and I don't know how to remove or put those up I searched for an solution on google and here but I failed.
Have anybody an idea how I can remove blank lines?
I tried it with:
currentLine.trim().length() == 0 ); but still with out success
Tanks
public static String COMMENT_LINE = "--.*";
public static String CREATE_BUFFERPOOL = "CREATE BUFFERPOOL.*";
public static String GRANT_USE = "GRANT USE.*";
public static String CONNECT_TO = "CONNECT TO.*";
public static Logger log = Logger.getLogger(Main.class);
//CHANGE PATH
public static String INPUT_FILE_PATH = "C://Users//dpa//Desktop//BW//bwcsvtest.txt";
public static String OUTPUT_FILE_PATH "C://Users//dpa//Desktop//BW//BWFormated.txt";
public static String TRANSFORM_FILE_PATH = "C://Users//dpa//Desktop//BW//BWtransformed.txt";
public static String CSV_FILE_PATH = "C://Users//dpa//Desktop//BW//result.csv";
public static void main(String[] args) throws IOException {
//log.debug("Formating File");
formatTxt(INPUT_FILE_PATH,OUTPUT_FILE_PATH);
log.debug("Formating File complete");
//CsvTransformer csvTransformer = new CsvTransformer(OUTPUT_FILE_PATH,TRANSFORM_FILE_PATH);
//csvTransformer.parseCSVInput();
//csvTransformer.writeDataToCsv(CSV_FILE_PATH);
}
public static void formatTxt(String inputFilePath, String outputFilePath) throws IOException {
File inputFile = new File(inputFilePath);
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
File tempFile = new File(outputFilePath);
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while ((currentLine = reader.readLine()) != null) {
currentLine = currentLine.trim();
if (currentLine.matches(COMMENT_LINE)) {
log.debug(currentLine);
log.debug("Commentline deleted");
continue;
}
if (currentLine.matches(CREATE_BUFFERPOOL)) {
log.debug(currentLine);
log.debug("CREATE BUFFERPOOL deleted");
continue;
}
if (currentLine.matches(GRANT_USE)) {
log.debug(currentLine);
log.debug("GRANT USE deleted");
continue;
}
if (currentLine.matches(CONNECT_TO)) {
log.debug(currentLine);
log.debug("CONNECT TO deleted");
continue;
}
writer.write(currentLine.replace("\t", ""));
writer.newLine();
}
reader.close();
writer.close();
}
}
Why not add, just after currentLine = currentLine.trim();, this code:
if (currentLine.isEmpty())
continue;
currentLine = currentLine.trim();
if (!currentLine .equals("")) // don't write out blank lines
{
writer.write(currentLine , 0, currentLine .length());
}