GVKun编程网logo

Python-如何跳至巨大文本文件中的特定行?(python跳转到指定行)

18

在本文中,我们将为您详细介绍是否可以将类中某个类的实例设置为null的相关知识,并且为您解答关于可以使一个类中定义的成员变量的疑问,此外,我们还会提供一些关于android–是否可以在onPostEx

在本文中,我们将为您详细介绍是否可以将类中某个类的实例设置为null的相关知识,并且为您解答关于可以使一个类中定义的成员变量的疑问,此外,我们还会提供一些关于android – 是否可以在onPostExecute()中将AsyncTask的引用设置为null?、c – 检查某个类是否可以转换为另一个类、c# – 是否可以将类中的扩展方法限制为特定类型?、Java的NullPointerException是否可以更改为报告哪个变量为null?的有用信息。

本文目录一览:

是否可以将类中某个类的实例设置为null(可以使一个类中定义的成员变量)

是否可以将类中某个类的实例设置为null(可以使一个类中定义的成员变量)

是否可以将类中某个类的实例设置为null。例如,我可以做这样的事情吗

int main{    //Create a new test object    Test test = new Test();    //Delete that object. This method should set the object "test" to null,     //thus allowing it to be called by the garbage collector.    test.delete();}public class Test{    public delete(){        this = null;    }}

我已经尝试过了,但是行不通。使用“ this = null”,我得到一个错误,即左侧必须是一个变量。有没有办法实现类似的目标?

答案1

小编典典

一个对象的实例不知道哪些引用可能在引用它,因此该对象中的代码无法使这些引用无效。您要的是不可能的(*)。

  • 至少没有添加一堆脚手架来跟踪所有参考,并且以某种方式通知其所有者应该将它们无效-绝不是“为了方便”。

android – 是否可以在onPostExecute()中将AsyncTask的引用设置为null?

android – 是否可以在onPostExecute()中将AsyncTask的引用设置为null?

我有一个Activity类,它有一个引用AsyncTask实例的属性,这个AsyncTask也有一个对这个Activity的引用.

从AsyncTask的onPostExecute()我想将Activity的引用设置为AsyncTask为null(通过将AsyncTask实例引用到Activity的引用).这是一个好习惯吗?

我在该方法的最后一行代码中执行此操作,因为我实际上是在向垃圾收集器说它可以删除该实例,因为它不再被任何其他对象(Activity)引用.这是正确的,还是我错了?

编辑:下面我的回答恢复了我使用的最终解决方案.

谢谢!

解决方法:

为什么你需要首先保持对AsyncTask的引用?

什么时候不再需要参考?在任务完成之前会发生什么需要您持有对活动的引用?

我所说的是,你可以在没有引用的情况下启动异步任务,这样你的问题就会消失.但如果由于某种原因你需要参考,那么通过更多地解释你的具体情况,我们可以建议一个更好的解决方案.

编辑

你主要关注的不是泄漏活动,而不是相反.如果你真的想要正确地清理所有引用,我会在异步任务上提供一个附加/分离方法,以便活动可以在nessecary时从异步任务中附加和分离自己,并且还提供一个使异步任务无效的活动方法如果活动仍然附加,则从您的异步任务中重新调用并调用它.不要直接做.异步任务不应直接修改活动.如果可能的话甚至将异步任务移动到新文件中,不要将其作为活动的内部类,这会导致泄漏.

c – 检查某个类是否可以转换为另一个类

c – 检查某个类是否可以转换为另一个类

如果我有模板功能

template<class T,class U>
T foo (U a);

如何检查是否可以将类U的对象类型转换为对象T.

那就是如果U类具有成员函数

operator T(); // Whatever T maybe

或者类T有一个构造函数

T(U& a); //ie constructs object with the help of the variable of type U

解决方法

您可以使用 std::is_convertible(自C 11起):

template<class T,class U>
T foo (U a) {
    if (std::is_convertible_v<U,T>) { /*...*/ }
    // ...
}

请注意,从C 17开始添加is_convertible_v,如果编译器仍然不支持它,则可以使用std :: is_convertible< U,T> :: value.

c# – 是否可以将类中的扩展方法限制为特定类型?

c# – 是否可以将类中的扩展方法限制为特定类型?

这种要求是由同伴开发人员将不同类型的扩展方法混合到一个xxxExt类中而引起的.
它仍然有效,因为编译器通过查看导入的命名空间来处理解决方案.但是当涉及重叠类型时,它很烦人并且不易维护.

是否可以约束可以在特定xxExt类中编写的类型扩展?循环手动规则不能很好地工作……如果不是编译器级别限制,可能就像静态代码分析一样?

代码(我想在这个类中限制IsActiveRisk方法).

public static class TradeDataExt{
     public static bool IsActiveTrade(this TradeData TradeData){...}

     public static bool IsActiveRisk(this RiskData riskData) {...}


}

这更像是一个“理想的”功能,不确定是否可能.
意见/建议会有所帮助.

解决方法

首先,在我看来你写了你的例子并忘记了扩展方法中更重要的关键字,你在参数之前错过了关键字“this”!

总结

以上是小编为你收集整理的c# – 是否可以将类中的扩展方法限制为特定类型?全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

Java的NullPointerException是否可以更改为报告哪个变量为null?

Java的NullPointerException是否可以更改为报告哪个变量为null?

NullPointerExceptionJava中,似乎只报告,它发生在一个特定的代码行。如果一行代码中使用了多个变量,是否可以更改该异常以声明哪个变量为null?

关于是否可以将类中某个类的实例设置为null可以使一个类中定义的成员变量的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于android – 是否可以在onPostExecute()中将AsyncTask的引用设置为null?、c – 检查某个类是否可以转换为另一个类、c# – 是否可以将类中的扩展方法限制为特定类型?、Java的NullPointerException是否可以更改为报告哪个变量为null?等相关内容,可以在本站寻找。

在这篇文章中,我们将为您详细介绍仅在Python中将datetime对象转换为日期字符串的内容,并且讨论关于python datetime转换为字符串的相关问题。此外,我们还会涉及一些关于Java中将字符串转换为日期Date对象、Python datetime格式化字符串到datetime对象、仅在 Python 中将 datetime 对象转换为日期字符串、使用 Joda Time 库将日期字符串转换为 DateTime 对象的知识,以帮助您更全面地了解这个主题。

本文目录一览:

仅在Python中将datetime对象转换为日期字符串(python datetime转换为字符串)

仅在Python中将datetime对象转换为日期字符串(python datetime转换为字符串)

在将日期字符串转换为datetimePython中的对象时,我看到了很多东西,但我想采用另一种方法。
我有

datetime.datetime(2019, 2, 23, 0, 0)

我想将其转换为类似的字符串''2/23/2019''

答案1

小编典典

你可以使用strftime来帮助设置日期格式。

例如,

import datetimet = datetime.datetime(2019, 2, 23, 0, 0)t.strftime(''%m/%d/%Y'')

将产生:

''02/23/2019''

Java中将字符串转换为日期Date对象

Java中将字符串转换为日期Date对象

实现思路:
       使用 SimpleDateFormat类 中的parse()方法即可将字符串转换为Date对象

使用参数化的方式接收字符串,并将字符串转Date对象

import java.util.*;
import java.text.*;
 
public class testClass{
 
    public static void main(String args[]) {
        SimpleDateFormat dateFormat_ = new SimpleDateFormat("yyyy-MM-dd");
        String s= args.length == 0 ? "2021-04-08" : args[0];
 
        System.out.print(s + " 解析为:");
        Date t;
        try {
            t = dateFormat_ .parse(input);
            System.out.println(t);
        } catch (ParseException e) {
            System.out.println("exception " + dateFormat_ );
        }
    }
}

 

Python datetime格式化字符串到datetime对象

Python datetime格式化字符串到datetime对象

我有一系列CSV,其中包含一个包含 Python日期时间格式字符串的列.在解析CSV文件(可能长达数万行)时,我希望将日期列从字符串转换为实际的日期时间对象.

CSV行示例:

['0','(2011,12,11,15,45,20)','Arduino/libraries/dallas-temperature-control/'],

如您所见,日期在日期时间格式的CSV中表示,但是以字符串形式表示.

我正在寻找一种快速的方法来构建datetime对象,而无需通过datetime.strptime运行它(row [1],“(%Y,%m,%d,%H,%M,%S)”) – 当它准备好按原样进行时,必须用strptime解释日期似乎是违反直觉的.

解决方法

您可以使用 ast.literal_eval将字符串转换为整数元组:

>>> import ast
>>> ast.literal_eval('(2011,20)')
(2011,20)

然后,您可以直接将此解压缩(请参见例如What does ** (double star) and * (star) do for parameters?)到datetime构造函数中:

>>> import datetime
>>> datetime.datetime(*ast.literal_eval('(2011,20)'))
datetime.datetime(2011,20)

仅在 Python 中将 datetime 对象转换为日期字符串

仅在 Python 中将 datetime 对象转换为日期字符串

我看到很多关于将日期字符串转换为datetimePython 中的对象的方法,但我想换一种方式。
我有

datetime.datetime(2012,2,23,0)

我想将它转换为字符串,如'2/23/2012'.

使用 Joda Time 库将日期字符串转换为 DateTime 对象

使用 Joda Time 库将日期字符串转换为 DateTime 对象

我有一个日期作为以下格式的字符串"04/02/2011 20:27:05"。我正在使用 Joda-Time
库并想将其转换为DateTime对象。我做了:

DateTime dt = new DateTime("04/02/2011 20:27:05")

但我收到以下错误:

Invalid format: "04/02/2011 14:42:17" is malformed at "/02/2011 14:42:17"

如何将上述日期转换为DateTime对象?

今天关于仅在Python中将datetime对象转换为日期字符串python datetime转换为字符串的分享就到这里,希望大家有所收获,若想了解更多关于Java中将字符串转换为日期Date对象、Python datetime格式化字符串到datetime对象、仅在 Python 中将 datetime 对象转换为日期字符串、使用 Joda Time 库将日期字符串转换为 DateTime 对象等相关知识,可以在本站进行查询。

针对如何重新计算JComponent的首选大小?这个问题,本篇文章进行了详细的解答,同时本文还将给你拓展Angular 2:如何在该Component中访问自定义Component的FormControl实例?、Angular应用里child Component如何向parent Component发送事件、com.intellij.openapi.components.BaseComponent的实例源码、com.intellij.openapi.components.ComponentConfig的实例源码等相关知识,希望可以帮助到你。

本文目录一览:

如何重新计算JComponent的首选大小?

如何重新计算JComponent的首选大小?

我知道这样的事实,当我创建JComponent的实例时,它具有自己的首选大小。现在,我们假设我手动设置了JComponent的PreferredSize,尺寸为0
x0。我希望该Component“重置”其自己的preferredSize。我怎么做?

答案1

小编典典

1)将首选大小设置为null可以将组件重置为重新计算其首选大小,就像从未设置过一样。

component.setPreferredSize(null);

这可能并不能满足您的要求,具体取决于您发出的信号是应该重做布局的方式-但至少从技术上讲,这是您问题的答案。

2)一般建议不要使用setPreferredSize,请参阅这篇文章

Angular 2:如何在该Component中访问自定义Component的FormControl实例?

Angular 2:如何在该Component中访问自定义Component的FormControl实例?

所以我一直在阅读如何在Angular2中构建自定义FormControls,但我无法得到我正在努力完成验证的工作.我有一个正常的输入控件,我想在自定义组件中包装,以便我可以这样做:

<my-control name="something" [(ngModel)]="model.something" required></my-control>

而不是每次都重复这个:

<divhttps://www.jb51.cc/tag/Feed/" target="_blank">Feedback" [ngClass]="{'has-success': someInput.valid,'has-error': someInput.invalid && someInput.dirty}">
    <labelfor="someId">{{label || 'Some Input'}}</label>
    <input type="test"id="someId" placeholder="Some Input" [ngModel]="value" (ngModel)="onChange($event)" name="someInput" required #someInput="ngModel" minlength="8"/>
    <spanhttps://www.jb51.cc/tag/Feed/" target="_blank">Feedback" aria-hidden="true" [ngClass]="{'glyphicon-ok': someInput.valid,'glyphicon-remove': someInput.invalid && someInput.dirty}"></span>
    <div [hidden]="someInput.valid || someInput.pristine || !someInput.errors.required">Some Input is required</div>
    <div [hidden]="someInput.valid || someInput.pristine || !someInput.errors.minlength">Some Input must be at least 8 characters</div>
</div>

所以我通过自定义组件实现了以下有关如何在线创建自定义组件的文章:

https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

缺少的是能够将验证移出组件,但允许自定义组件处理该验证的显示.因此,如果你看一下我的目的是允许组件的用户指定验证而不是让组件强加特定的验证(注意某些验证是组件固有的,例如电子邮件地址组件会验证它是一封没有用户指定的电子邮件).请注意,必需的是该客户组件的使用情况.

那么如何在该组件的定义中获得对自定义组件的FormControl的引用?注意:我理解如何访问模板的FormControl实例中的输入字段,因为上面的代码完全证明了这一点.我要求的是模板所在的自定义控件的FormControl实例.在我引用的文章中,它将是CounterInputComponent的FormControl.

解决方法

添加这似乎工作:

@ViewChild(NgModel) model: NgModel;

然后你可以通过以下方式访问FormControl:

this.model.control

Angular应用里child Component如何向parent Component发送事件

Angular应用里child Component如何向parent Component发送事件

detail Component里,使用event binding,给button click事件注册一个处理函数delete:

<img src="{
    
    
    {itemImageUrl}}" [style.display]="displayNone">
<span [style.text-decoration]="lineThrough">{
  
  
  { item.name }}
</span>
<button (click)="delete()">Delete</button>
@Output() deleteRequest = new EventEmitter<Item>();

delete() {
   
   
   
  this.deleteRequest.emit(this.item);
  this.displayNone = this.displayNone ? '''' : ''none'';
  this.lineThrough = this.lineThrough ? '''' : ''line-through'';
}

在delete函数里,使用EventEmitter发送一个事件。deleteRequest这个property需要加上@Output的注解。

在parent Component里,监听从child Component发送过来的自定义事件:

<app-item-detail (deleteRequest)="deleteItem($event)" [item]="currentItem"></app-item-detail>

本文分享 CSDN - 汪子熙。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

com.intellij.openapi.components.BaseComponent的实例源码

com.intellij.openapi.components.BaseComponent的实例源码

项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
private void registerComponentInstance(@NotNull Object instance) {
  myInstantiatedComponentCount++;

  if (instance instanceof com.intellij.openapi.disposable) {
    disposer.register(this,(com.intellij.openapi.disposable)instance);
  }

  if (!(instance instanceof BaseComponent)) {
    return;
  }

  BaseComponent baseComponent = (BaseComponent)instance;
  String componentName = baseComponent.getComponentName();
  if (myNametoComponent.containsKey(componentName)) {
    BaseComponent loadedComponent = myNametoComponent.get(componentName);
    // component may have been already loaded by picocontainer,so fire error only if components are really different
    if (!instance.equals(loadedComponent)) {
      LOG.error("Component name collision: " + componentName + " " + loadedComponent.getClass() + " and " + instance.getClass());
    }
  }
  else {
    myNametoComponent.put(componentName,baseComponent);
  }

  myBaseComponents.add(baseComponent);
}
项目:intellij-ce-playground    文件:VcsEP.java   
@Nullable
private AbstractVcs getInstance(@NotNull Project project,@NotNull String vcsClass) {
  try {
    final Class<? extends AbstractVcs> foundClass = findClass(vcsClass);
    final Class<?>[] interfaces = foundClass.getInterfaces();
    for (Class<?> anInterface : interfaces) {
      if (BaseComponent.class.isAssignableFrom(anInterface)) {
        return PeriodicalTasksCloser.getInstance().safeGetComponent(project,foundClass);
      }
    }
    return instantiate(vcsClass,project.getpicocontainer());
  }
  catch (ProcessCanceledException pce) {
    throw pce;
  }
  catch(Exception e) {
    LOG.error(e);
    return null;
  }
}
项目:tools-idea    文件:VcsEP.java   
public AbstractVcs getVcs(Project project) {
  if (myVcs == null) {
    try {
      final Class<? extends AbstractVcs> foundClass = findClass(vcsClass);
      final Class<?>[] interfaces = foundClass.getInterfaces();
      for (Class<?> anInterface : interfaces) {
        if (BaseComponent.class.isAssignableFrom(anInterface)) {
          myVcs = PeriodicalTasksCloser.getInstance().safeGetComponent(project,foundClass);
          myVcs = VcsActiveEnvironmentsProxy.proxyVcs(myVcs);
          return myVcs;
        }
      }
      myVcs = VcsActiveEnvironmentsProxy.proxyVcs((AbstractVcs)instantiate(vcsClass,project.getpicocontainer()));
    }
    catch(Exception e) {
      LOG.error(e);
      return null;
    }
  }
  return myVcs;
}
项目:consulo    文件:VcsEP.java   
@Nullable
private AbstractVcs getInstance(@Nonnull Project project,@Nonnull String vcsClass) {
  try {
    final Class<? extends AbstractVcs> foundClass = findClass(vcsClass);
    final Class<?>[] interfaces = foundClass.getInterfaces();
    for (Class<?> anInterface : interfaces) {
      if (BaseComponent.class.isAssignableFrom(anInterface)) {
        return PeriodicalTasksCloser.getInstance().safeGetComponent(project,project.getpicocontainer());
  }
  catch (ProcessCanceledException pce) {
    throw pce;
  }
  catch(Exception e) {
    LOG.error(e);
    return null;
  }
}
项目:intellij-ce-playground    文件:SnapShooterConfigurationExtension.java   
@Override
public void updateJavaParameters(runconfigurationBase configuration,JavaParameters params,RunnerSettings runnerSettings) {
  if (!isApplicableFor(configuration)) {
    return;
  }
  ApplicationConfiguration appConfiguration = (ApplicationConfiguration) configuration;
  SnapShooterConfigurationSettings settings = appConfiguration.getUserData(SnapShooterConfigurationSettings.SNAP_SHOOTER_KEY);
  if (settings == null) {
    settings = new SnapShooterConfigurationSettings();
    appConfiguration.putUserData(SnapShooterConfigurationSettings.SNAP_SHOOTER_KEY,settings);
  }
  if (appConfiguration.ENABLE_SWING_INSPECTOR) {
    settings.setLastPort(NetUtils.tryToFindAvailableSocketPort());
  }

  if (appConfiguration.ENABLE_SWING_INSPECTOR && settings.getLastPort() != -1) {
    params.getProgramParametersList().prepend(appConfiguration.MAIN_CLASS_NAME);
    params.getProgramParametersList().prepend(Integer.toString(settings.getLastPort()));
    // add +1 because idea_rt.jar will be added as the last entry to the classpath
    params.getProgramParametersList().prepend(Integer.toString(params.getClasspath().getPathList().size() + 1));
    Set<String> paths = new TreeSet<String>();
    paths.add(PathUtil.getJarPathForClass(SnapShooter.class));         // ui-designer-impl
    paths.add(PathUtil.getJarPathForClass(BaseComponent.class));       // appcore-api
    paths.add(PathUtil.getJarPathForClass(ProjectComponent.class));    // openapi
    paths.add(PathUtil.getJarPathForClass(LwComponent.class));         // UIDesignerCore
    paths.add(PathUtil.getJarPathForClass(GridConstraints.class));     // forms_rt
    paths.add(PathUtil.getJarPathForClass(PaletteGroup.class));        // openapi
    paths.add(PathUtil.getJarPathForClass(LafManagerListener.class));  // ui-impl
    paths.add(PathUtil.getJarPathForClass(DataProvider.class));        // action-system-openapi
    paths.add(PathUtil.getJarPathForClass(XmlStringUtil.class));       // idea
    paths.add(PathUtil.getJarPathForClass(Navigatable.class));         // pom
    paths.add(PathUtil.getJarPathForClass(AreaInstance.class));        // extensions
    paths.add(PathUtil.getJarPathForClass(Formlayout.class));          // jgoodies
    paths.addAll(PathManager.getUtilClasspath());
    for(String path: paths) {
      params.getClasspath().addFirst(path);
    }
    params.setMainClass("com.intellij.uiDesigner.snapShooter.SnapShooter");
  }
}
项目:intellij-ce-playground    文件:ComponentType.java   
ComponentType(Class<? extends BaseComponent> clazz,@NonNls String name,@PropertyKey(resourceBundle = "org.jetbrains.idea.devkit.DevKitBundle") String propertyKey)
{
  myPropertyKey = propertyKey;
  myClassName = clazz.getName();
  myName = name;
}
项目:tools-idea    文件:ComponentType.java   
ComponentType(Class<? extends BaseComponent> clazz,@PropertyKey(resourceBundle = "org.jetbrains.idea.devkit.DevKitBundle") String propertyKey)
{
  myPropertyKey = propertyKey;
  myClassName = clazz.getName();
  myName = name;
}
项目:jfrog-idea-plugin    文件:NpmProjectImpl.java   
@Override
public BaseComponent getComponent(@NotNull String name) {
    return null;
}
项目:stack-intheflow    文件:ProjectMock.java   
@Override
public BaseComponent getComponent(@NotNull String s) {
    return null;
}
项目:intellij-ce-playground    文件:DummyProject.java   
@Override
public BaseComponent getComponent(@NotNull String name) {
  return null;
}
项目:intellij-ce-playground    文件:MockComponentManager.java   
@Override
public BaseComponent getComponent(@NotNull String name) {
  return null;
}
项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
@Override
public synchronized BaseComponent getComponent(@NotNull String name) {
  return myNametoComponent.get(name);
}
项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
@Override
public Object getComponentInstance(picocontainer picocontainer) throws PicoInitializationException,PicoIntrospectionException,ProcessCanceledException {
  Object instance = myInitializedComponentInstance;
  if (instance != null) {
    return instance;
  }

  try {
    //noinspection SynchronizeOnThis
    synchronized (this) {
      instance = myInitializedComponentInstance;
      if (instance != null) {
        return instance;
      }

      long startTime = System.nanoTime();

      instance = super.getComponentInstance(picocontainer);

      if (myInitializing) {
        String errorMessage = "Cyclic component initialization: " + getComponentKey();
        if (myPluginId != null) {
          LOG.error(new PluginException(errorMessage,myPluginId));
        }
        else {
          LOG.error(new Throwable(errorMessage));
        }
      }

      try {
        myInitializing = true;
        registerComponentInstance(instance);

        ProgressIndicator indicator = getProgressIndicator();
        if (indicator != null) {
          indicator.checkCanceled();
          setProgressDuringInit(indicator);
        }
        initializeComponent(instance,false);
        if (instance instanceof BaseComponent) {
          ((BaseComponent)instance).initComponent();
        }

        long ms = (System.nanoTime() - startTime) / 1000000;
        if (ms > 10 && logSlowComponents()) {
          LOG.info(instance.getClass().getName() + " initialized in " + ms + " ms");
        }
      }
      finally {
        myInitializing = false;
      }
      myInitializedComponentInstance = instance;
    }
  }
  catch (ProcessCanceledException e) {
    throw e;
  }
  catch (Throwable t) {
    handleInitComponentError(t,((Class)getComponentKey()).getName(),myPluginId);
  }

  return instance;
}
项目:aem-ide-tooling-4-intellij    文件:MockProject.java   
@Override
public BaseComponent getComponent(@NotNull String s) {
    return null;
}
项目:shared-views    文件:MockProject.java   
@Override
public BaseComponent getComponent(@NotNull String name) {
    return null;
}
项目:tools-idea    文件:DummyProject.java   
@Override
public BaseComponent getComponent(@NotNull String name) {
  return null;
}
项目:tools-idea    文件:MockComponentManager.java   
@Override
public BaseComponent getComponent(@NotNull String name) {
  return null;
}
项目:tools-idea    文件:MockProject.java   
@Override
public BaseComponent getComponent(@NotNull String name) {
  throw new UnsupportedOperationException();
}
项目:tools-idea    文件:SnapShooterConfigurationExtension.java   
@Override
public void updateJavaParameters(runconfigurationBase configuration,settings);
  }
  if (appConfiguration.ENABLE_SWING_INSPECTOR) {
    try {
      settings.setLastPort(NetUtils.findAvailableSocketPort());
    }
    catch(IOException ex) {
      settings.setLastPort(-1);
    }
  }

  if (appConfiguration.ENABLE_SWING_INSPECTOR && settings.getLastPort() != -1) {
    params.getProgramParametersList().prepend(appConfiguration.MAIN_CLASS_NAME);
    params.getProgramParametersList().prepend(Integer.toString(settings.getLastPort()));
    // add +1 because idea_rt.jar will be added as the last entry to the classpath
    params.getProgramParametersList().prepend(Integer.toString(params.getClasspath().getPathList().size() + 1));
    Set<String> paths = new TreeSet<String>();
    paths.add(PathUtil.getJarPathForClass(SnapShooter.class));         // ui-designer-impl
    paths.add(PathUtil.getJarPathForClass(BaseComponent.class));       // appcore-api
    paths.add(PathUtil.getJarPathForClass(ProjectComponent.class));    // openapi
    paths.add(PathUtil.getJarPathForClass(LwComponent.class));         // UIDesignerCore
    paths.add(PathUtil.getJarPathForClass(GridConstraints.class));     // forms_rt
    paths.add(PathUtil.getJarPathForClass(LafManagerListener.class));  // ui-impl
    paths.add(PathUtil.getJarPathForClass(DataProvider.class));        // action-system-openapi
    paths.add(PathUtil.getJarPathForClass(XmlStringUtil.class));       // idea
    paths.add(PathUtil.getJarPathForClass(Navigatable.class));         // pom
    paths.add(PathUtil.getJarPathForClass(AreaInstance.class));        // extensions
    paths.add(PathUtil.getJarPathForClass(Formlayout.class));          // jgoodies
    paths.addAll(PathManager.getUtilClasspath());
    for(String path: paths) {
      params.getClasspath().addFirst(path);
    }
    params.setMainClass("com.intellij.uiDesigner.snapShooter.SnapShooter");
  }
}
项目:EclipseCodeFormatter    文件:StringUtilsTest.java   
@Override
public BaseComponent getComponent(String name) {
    return null;
}
项目:consulo-ui-designer    文件:SnapShooterConfigurationExtension.java   
@Override
public void updateJavaParameters(runconfigurationBase configuration,OwnJavaParameters params,settings);
  }
  if (appConfiguration.ENABLE_SWING_INSPECTOR) {
    try {
      settings.setLastPort(NetUtils.findAvailableSocketPort());
    }
    catch(IOException ex) {
      settings.setLastPort(-1);
    }
  }

  if (appConfiguration.ENABLE_SWING_INSPECTOR && settings.getLastPort() != -1) {
    params.getProgramParametersList().prepend(appConfiguration.MAIN_CLASS_NAME);
    params.getProgramParametersList().prepend(Integer.toString(settings.getLastPort()));
    // add +1 because idea_rt.jar will be added as the last entry to the classpath
    params.getProgramParametersList().prepend(Integer.toString(params.getClasspath().getPathList().size() + 1));
    Set<String> paths = new TreeSet<String>();
    paths.add(PathUtil.getJarPathForClass(SnapShooter.class));         // ui-designer-impl
    paths.add(PathUtil.getJarPathForClass(BaseComponent.class));       // appcore-api
    paths.add(PathUtil.getJarPathForClass(ProjectComponent.class));    // openapi
    paths.add(PathUtil.getJarPathForClass(LwComponent.class));         // UIDesignerCore
    paths.add(PathUtil.getJarPathForClass(GridConstraints.class));     // forms_rt
    paths.add(PathUtil.getJarPathForClass(LafManagerListener.class));  // ui-impl
    paths.add(PathUtil.getJarPathForClass(DataProvider.class));        // action-system-openapi
    paths.add(PathUtil.getJarPathForClass(XmlStringUtil.class));       // idea
    paths.add(PathUtil.getJarPathForClass(Navigatable.class));         // pom
    paths.add(PathUtil.getJarPathForClass(AreaInstance.class));        // extensions
    paths.add(PathUtil.getJarPathForClass(Formlayout.class));          // jgoodies
    paths.addAll(PathManager.getUtilClasspath());
    for(String path: paths) {
      params.getClasspath().addFirst(path);
    }
    params.setMainClass("com.intellij.uiDesigner.snapShooter.SnapShooter");
  }
}
项目:consulo    文件:MockProject.java   
@Override
public BaseComponent getComponent(String name) {
  throw new UnsupportedOperationException();
}
项目:consulo    文件:DummyProject.java   
@Override
public BaseComponent getComponent(String name) {
  return null;
}
项目:consulo    文件:MockComponentManager.java   
@Override
public BaseComponent getComponent(@Nonnull String name) {
  return null;
}

com.intellij.openapi.components.ComponentConfig的实例源码

com.intellij.openapi.components.ComponentConfig的实例源码

项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
protected final void init(@Nullable ProgressIndicator indicator,@Nullable Runnable componentsRegistered) {
  List<ComponentConfig> componentConfigs = getComponentConfigs();
  for (ComponentConfig config : componentConfigs) {
    registerComponents(config);
  }
  myComponentConfigCount = componentConfigs.size();

  if (componentsRegistered != null) {
    componentsRegistered.run();
  }

  if (indicator != null) {
    indicator.setIndeterminate(false);
  }
  createComponents(indicator);
  myComponentsCreated = true;
}
项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
@NotNull
private List<ComponentConfig> getComponentConfigs() {
  ArrayList<ComponentConfig> componentConfigs = new ArrayList<ComponentConfig>();
  boolean isDefaultProject = this instanceof Project && ((Project)this).isDefault();
  boolean headless = ApplicationManager.getApplication().isHeadlessEnvironment();
  for (IdeaPluginDescriptor plugin : PluginManagerCore.getPlugins()) {
    if (PluginManagerCore.shouldSkipPlugin(plugin)) {
      continue;
    }

    ComponentConfig[] configs = getMyComponentConfigsFromDescriptor(plugin);
    componentConfigs.ensureCapacity(componentConfigs.size() + configs.length);
    for (ComponentConfig config : configs) {
      if ((!isDefaultProject || config.isLoadForDefaultProject()) && isComponentSuitable(config.options) && config.prepareClasses(headless)) {
        config.pluginDescriptor = plugin;
        componentConfigs.add(config);
      }
    }
  }
  return componentConfigs;
}
项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
private void registerComponents(@NotNull ComponentConfig config) {
  ClassLoader loader = config.getClassLoader();
  try {
    final Class<?> interfaceClass = Class.forName(config.getInterfaceClass(),true,loader);
    final Class<?> implementationClass = Comparing.equal(config.getInterfaceClass(),config.getImplementationClass())
                                         ?
                                         interfaceClass
                                         : StringUtil.isEmpty(config.getImplementationClass()) ? null : Class.forName(config.getImplementationClass(),loader);
    Mutablepicocontainer picocontainer = getpicocontainer();
    if (config.options != null && Boolean.parseBoolean(config.options.get("overrides"))) {
      ComponentAdapter oldAdapter = picocontainer.getComponentAdapterOfType(interfaceClass);
      if (oldAdapter == null) {
        throw new RuntimeException(config + " does not override anything");
      }
      picocontainer.unregisterComponent(oldAdapter.getComponentKey());
    }
    // implementationClass == null means we want to unregister this component
    if (implementationClass != null) {
      picocontainer.registerComponent(new ComponentConfigComponentAdapter(interfaceClass,implementationClass,config.getPluginId(),config.options != null && Boolean.parseBoolean(config.options.get("workspace"))));
    }
  }
  catch (Throwable t) {
    handleInitComponentError(t,null,config.getPluginId());
  }
}
项目:tools-idea    文件:PluginManager.java   
public static void handleComponentError(Throwable t,String componentClassName,ComponentConfig config) {
  if (t instanceof StartupAbortedException) {
    throw (StartupAbortedException)t;
  }

  PluginId pluginId = config != null ? config.getPluginId() : getPluginByClassName(componentClassName);

  if (pluginId != null && !CORE_PLUGIN_ID.equals(pluginId.getIdString())) {
    getLogger().warn(t);

    disablePlugin(pluginId.getIdString());

    String message =
      "Plugin '" + pluginId.getIdString() + "' Failed to initialize and will be disabled\n" +
      "(reason: " + t.getMessage() + ")\n\n" +
      ApplicationNamesInfo.getInstance().getFullProductName() + " will be restarted.";
    Main.showMessage("Plugin Error",message,false);

    throw new StartupAbortedException(t).exitCode(Main.PLUGIN_ERROR).logError(false);
  }
  else {
    throw new StartupAbortedException("Fatal error initializing '" + componentClassName + "'",t);
  }
}
项目:intellij-ce-playground    文件:IdeaPluginDescriptorImpl.java   
private static ComponentConfig[] mergeComponents(ComponentConfig[] first,ComponentConfig[] second) {
  if (first == null) {
    return second;
  }
  if (second == null) {
    return first;
  }
  return ArrayUtil.mergeArrays(first,second);
}
项目:tools-idea    文件:ApplicationImpl.java   
@Override
protected void handleInitComponentError(Throwable t,ComponentConfig config) {
  if (!myHandlingInitComponentError) {
    myHandlingInitComponentError = true;
    try {
      PluginManager.handleComponentError(t,componentClassName,config);
    }
    finally {
      myHandlingInitComponentError = false;
    }
  }
}
项目:tools-idea    文件:ComponentManagerConfigurator.java   
public void loadComponentsConfiguration(final ComponentConfig[] components,final PluginDescriptor descriptor,final boolean defaultProject) {
  if (components == null) return;

  loadConfiguration(components,defaultProject,descriptor);
}
项目:tools-idea    文件:IdeaPluginDescriptorImpl.java   
private static ComponentConfig[] mergeComponents(ComponentConfig[] first,second);
}
项目:consulo    文件:PlatformComponentManagerImpl.java   
@Override
protected void handleInitComponentError(@Nonnull Throwable ex,@Nullable String componentClassName,@Nullable ComponentConfig config) {
  if (!myHandlingInitComponentError) {
    myHandlingInitComponentError = true;
    try {
      PluginManager.handleComponentError(ex,config);
    }
    finally {
      myHandlingInitComponentError = false;
    }
  }
}
项目:consulo    文件:PluginManager.java   
public static void handleComponentError(@Nonnull Throwable t,@Nullable ComponentConfig config) {
  if (t instanceof StartupAbortedException) {
    throw (StartupAbortedException)t;
  }

  PluginId pluginId = null;
  if (config != null) {
    pluginId = config.getPluginId();
  }
  if (pluginId == null || CORE_PLUGIN.equals(pluginId)) {
    pluginId = componentClassName == null ? null : getPluginByClassName(componentClassName);
  }
  if (pluginId == null || CORE_PLUGIN.equals(pluginId)) {
    if (t instanceof PicopluginExtensionInitializationException) {
      pluginId = ((PicopluginExtensionInitializationException)t).getPluginId();
    }
  }

  if (pluginId != null && !isSystemPlugin(pluginId)) {
    getLogger().warn(t);

    if(!ApplicationProperties.isInSandBox()) {
      disablePlugin(pluginId.getIdString());
    }

    StringWriter message = new StringWriter();
    message.append("Plugin '").append(pluginId.getIdString()).append("' Failed to initialize and will be disabled. ");
    message.append(" Please restart ").append(ApplicationNamesInfo.getInstance().getFullProductName()).append('.');
    message.append("\n\n");
    t.printstacktrace(new PrintWriter(message));
    Main.showMessage("Plugin Error",message.toString(),t);
  }
}
项目:consulo    文件:ComponentManagerConfigurator.java   
public void loadComponentsConfiguration(final ComponentConfig[] components,descriptor);
}
项目:consulo    文件:IdeaPluginDescriptorImpl.java   
private static ComponentConfig[] mergeComponents(ComponentConfig[] first,second);
}
项目:intellij-ce-playground    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getAppComponents();
项目:intellij-ce-playground    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getProjectComponents();
项目:intellij-ce-playground    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getModuleComponents();
项目:intellij-ce-playground    文件:ApplicationImpl.java   
@NotNull
@Override
public ComponentConfig[] getMyComponentConfigsFromDescriptor(@NotNull IdeaPluginDescriptor plugin) {
  return plugin.getAppComponents();
}
项目:intellij-ce-playground    文件:DummyProject.java   
@NotNull
public ComponentConfig[] getComponentConfigurations() {
  return new ComponentConfig[0];
}
项目:intellij-ce-playground    文件:DummyProject.java   
@Nullable
public Object getComponent(final ComponentConfig componentConfig) {
  return null;
}
项目:intellij-ce-playground    文件:DummyProject.java   
public ComponentConfig getConfig(Class componentImplementation) {
  throw new UnsupportedOperationException("Method getConfig not implemented in " + getClass());
}
项目:intellij-ce-playground    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getAppComponents() {
  throw new IllegalStateException();
}
项目:intellij-ce-playground    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getProjectComponents() {
  throw new IllegalStateException();
}
项目:intellij-ce-playground    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getModuleComponents() {
  throw new IllegalStateException();
}
项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
@NotNull
public ComponentConfig[] getMyComponentConfigsFromDescriptor(@NotNull IdeaPluginDescriptor plugin) {
  return plugin.getAppComponents();
}
项目:intellij-ce-playground    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getAppComponents() {
  return myAppComponents;
}
项目:intellij-ce-playground    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getProjectComponents() {
  return myProjectComponents;
}
项目:intellij-ce-playground    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getModuleComponents() {
  return myModuleComponents;
}
项目:tools-idea    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getAppComponents();
项目:tools-idea    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getProjectComponents();
项目:tools-idea    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getModuleComponents();
项目:tools-idea    文件:DummyProject.java   
@NotNull
public ComponentConfig[] getComponentConfigurations() {
  return new ComponentConfig[0];
}
项目:tools-idea    文件:DummyProject.java   
@Nullable
public Object getComponent(final ComponentConfig componentConfig) {
  return null;
}
项目:tools-idea    文件:DummyProject.java   
public ComponentConfig getConfig(Class componentImplementation) {
  throw new UnsupportedOperationException("Method getConfig not implemented in " + getClass());
}
项目:tools-idea    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getAppComponents() {
  throw new IllegalStateException();
}
项目:tools-idea    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getProjectComponents() {
  throw new IllegalStateException();
}
项目:tools-idea    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getModuleComponents() {
  throw new IllegalStateException();
}
项目:tools-idea    文件:ComponentManagerConfigurator.java   
private void loadConfiguration(final ComponentConfig[] configs,final boolean defaultProject,final PluginDescriptor descriptor) {
  for (ComponentConfig config : configs) {
    loadSingleConfig(defaultProject,config,descriptor);
  }
}
项目:tools-idea    文件:ComponentManagerConfigurator.java   
private void loadSingleConfig(final boolean defaultProject,final ComponentConfig config,final PluginDescriptor descriptor) {
  if (defaultProject && !config.isLoadForDefaultProject()) return;
  if (!myComponentManager.isComponentSuitable(config.options)) return;

  myComponentManager.registerComponent(config,descriptor);
}
项目:tools-idea    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getAppComponents() {
  return myAppComponents;
}
项目:tools-idea    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getProjectComponents() {
  return myProjectComponents;
}
项目:tools-idea    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getModuleComponents() {
  return myModuleComponents;
}

今天关于如何重新计算JComponent的首选大小?的分享就到这里,希望大家有所收获,若想了解更多关于Angular 2:如何在该Component中访问自定义Component的FormControl实例?、Angular应用里child Component如何向parent Component发送事件、com.intellij.openapi.components.BaseComponent的实例源码、com.intellij.openapi.components.ComponentConfig的实例源码等相关知识,可以在本站进行查询。

在本文中,我们将给您介绍关于XX:+ HeapDumpOnOutOfMemoryError最大文件大小限制的详细内容,并且为您解答文件大小超出4194303块的最大数的相关问题,此外,我们还将为您提供关于-XX:HeapDumpOnOutOfMemoryError、Apache PDFBOX-使用split(PDDocument文档)时出现java.lang.OutOfMemoryError、flume遇到java.lang.OutOfMemoryError: Java heap space、HeapDumpOnOutOfMemoryError 使用的知识。

本文目录一览:

XX:+ HeapDumpOnOutOfMemoryError最大文件大小限制(文件大小超出4194303块的最大数)

XX:+ HeapDumpOnOutOfMemoryError最大文件大小限制(文件大小超出4194303块的最大数)

我正在使用XX:+HeapDumpOnOutOfMemoryErrorJVM标志运行Java进程,并看到以下输出:

java.lang.OutOfMemoryError: Java heap spaceDumping heap to /local/disk2/heaps/heapdump.hprof ...Dump file is incomplete: file size limit

有没有办法解决这个问题?

答案1

小编典典

-XX:+HeapDumpOnOutOfMemoryError当无法满足Java堆的分配或永久生成时,命令行选项告诉HotSpot
VM生成堆转储。使用此选项运行不会产生任何开销,因此对于OutOfMemoryError需要很长时间才能浮出水面的生产系统很有用。

为了解决您面临的特定问题,可以使用以下纠正措施之一:

措施1: XX:HeapDumpSegmentSize

-XX:HeapDumpSegmentSize选项在生成分段的HPROF堆转储时指定适当的段大小。

格式

-XX:HeapDumpSegmentSize =大小[k | K] [m | M] [g | G]

java -XX:+HeapDumpOnOutOfMemory -XX:HeapDumpSegmentSize=512M myApp

预设值
1 GB

措施2 -XX:SegmentedHeapDumpThreshold

当堆使用量大于指定大小时,-XX:SegmentedHeapDumpThreshold选项将生成分段堆转储(.hprof文件,1.0.2格式)。

需要分段的HPROF转储格式才能正确生成包含4 GB以上数据的堆转储。如果-XX:SegmentedHeapDumpThreshold选项的值设置为大于4
GB,则可能无法正确生成堆转储。

格式
-XX:SegmentedHeapDumpThreshold =大小

java -XX:SegmentedHeapDumpThreshold=512M myApp

默认值
2 GB

-XX:HeapDumpOnOutOfMemoryError

-XX:HeapDumpOnOutOfMemoryError

用法: -XX:+HeapDumpOnOutOfMemoryError 当堆抛出OOM错误时,dump出当前的内存堆转储快照。

举个栗子

public class OOM {

    static class OOMObject {

    }

    //-Xmx20M -Xms20M -XX:+HeapDumpOnOutOfMemoryError -XX:+UseParNewGC -XX:+UseConcMarkSweepGC
    public static void main(String[] args) {
        List<OOMObject> list = new LinkedList<>();
        while(true) {
            list.add(new OOMObject());
        }
    }

}

这个例子很简单,就是不断创建OOMObject,加入到list中(为了让GC Roots到对象之间有可达路径,避免被GC),直到堆内存不够时,抛出OOM异常。

运行后,控制台打印信息

java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid97312.hprof ... 
Heap dump file created [33684485 bytes in 0.424 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at com.gc.OOM.main(OOM.java:19)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

可以看到dump出了hprof文件可供分析,可以用MAT工具进行分析

用MAT打开后,可以看到分析情况

image.png

image.png

由此也可以知道,是因为list的容量过大而导致OOM,可以根据此来进行优化代码或者JVM参数。

如果是由内存泄漏导致的,也可以通过工具查看泄漏对象到GC Roots的引用链,就能进行相应的分析处理。

另一个与之相关联的参数: -XX:HeapDumpPath=/temp/ 该参数的含义是指定dump的文件目录

Apache PDFBOX-使用split(PDDocument文档)时出现java.lang.OutOfMemoryError

Apache PDFBOX-使用split(PDDocument文档)时出现java.lang.OutOfMemoryError

我正在尝试使用Apache PDFBOX API V2.0.2拆分300页的文档。尝试使用以下代码将pdf文件拆分为单个页面时:

        PDDocument document = PDDocument.load(inputFile);
        Splitter splitter = new Splitter();
        List<PDDocument> splittedDocuments = splitter.split(document); //Exception happens here

我收到以下异常

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

这表明GC需要花费大量时间来清除没有被回收量证明合理的堆。

有许多JVM调优方法可以解决这种情况,但是,所有这些方法都只是在解决症状而不是真正的问题。

最后一点,我正在使用JDK6,因此在我的情况下,不能使用新的Java 8 Consumer。

编辑:

这不是http://codingdict.com/questions/159530的重复问题,如下所示:

 1.我没有上述提到的尺寸问题
    话题。我将270页的13.8MB切片,然后切片
    每个切片的大小平均为80KB,总大小为
    30.7兆字节
 2.即使在拆分之前,拆分也会引发异常。

我发现只要不传递整个文档,拆分就可以通过,而是将其作为“批量”传递,每个批量20-30页,即可完成工作。

flume遇到java.lang.OutOfMemoryError: Java heap space

flume遇到java.lang.OutOfMemoryError: Java heap space

当使用flume-ng进行日志采集的时候,如果日志文件很大,容易导致flume出现:

java.lang.OutOfMemoryError: Java heap space 产生这样错误主要是内存的原因,

1 因为我的channel是存在内存中的,所以我修改了flume的配置文件,将channel修改为file, 另外需要调整flume相应的jvm启动参数。

2 修改 flume下的conf/flume-env.sh文件:

export JAVA_OPTS="-Xms512m -Xmx1024m -Dcom.sun.management.jmxremote" 其中:

-Xms<size> set initial Java heap size......................... -Xmx<size> set maximum Java heap size.........................

主要修改Xmx和Xms两个参数,可以根据OS内存的大小进行合理设置,一般一个flume agent 1G左右大小即可


如果有flume问题,请加QQ群:140467035 ,共同学习进步

HeapDumpOnOutOfMemoryError 使用

HeapDumpOnOutOfMemoryError 使用

将堆的最小值-Xms参数与最大值-Xmx参数设置为一样即可避免堆自动扩

展.

https://my.oschina.net/xiangtao/blog/511622

https://my.oschina.net/13510434519/blog/850101

https://my.oschina.net/u/3110327/blog/850521

https://blog.csdn.net/pfnie/article/details/52766204?locationNum=13&fps=1

重点是确认内存中的对象是否是必要的,也就是要先分清楚到底是出现了内存泄漏(Memory Leak)还是内存溢出(Memory 

Overflow)。

如果是内存泄漏,可进一步通过工具查看泄漏对象到GC Roots的引用链。于是就能找到泄漏对象是通过怎样的路径与GC Roots相关

联并导致垃圾收集器无法自动回收它们的。掌握了泄漏对象的类型信息,以及GC Roots引用链的信息,就可以比较准确地定位出泄

漏代码的位置。


如果不存在泄漏,换句话说就是内存中的对象确实都还必须存活着,那就应当检查虚拟机的堆参数(-Xmx与-Xms),与机器物理内

存对比看是否还可以调大,从代码上检查是否存在某些对象生命周期过长、持有状态时间过长的情况,尝试减少程序运行期的内存

消耗。


《深入理解java虚拟机》

关于XX:+ HeapDumpOnOutOfMemoryError最大文件大小限制文件大小超出4194303块的最大数的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于-XX:HeapDumpOnOutOfMemoryError、Apache PDFBOX-使用split(PDDocument文档)时出现java.lang.OutOfMemoryError、flume遇到java.lang.OutOfMemoryError: Java heap space、HeapDumpOnOutOfMemoryError 使用等相关知识的信息别忘了在本站进行查找喔。

对于Python-如何跳至巨大文本文件中的特定行?感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍python跳转到指定行,并为您提供关于c# – 如何跳转到RichTextBox中的特定行?、linux – 如何使用shell脚本将文本附加到文件中的特定行?、perl – 如何在Unix中打印文件中的特定行?、python如何写入现有txt文件中的特定行的有用信息。

本文目录一览:

Python-如何跳至巨大文本文件中的特定行?(python跳转到指定行)

Python-如何跳至巨大文本文件中的特定行?(python跳转到指定行)

以下代码是否有替代方法:

startFromLine = 141978 # or whatever line I need to jump tourlsfile = open(filename, "rb", 0)linesCounter = 1for line in urlsfile:    if linesCounter > startFromLine:        DoSomethingWithThisLine(line)    linesCounter += 1

如果我正在处理一个巨大的文本文件(~15MB),其行数未知但长度不同,并且需要跳转到特定行我应该事先知道哪个号码?当我知道我至少可以忽略文件的前半部分时,我很难一一处理它们。寻找更优雅的解决方案(如果有)。

答案1

小编典典

由于你不知道换行符在哪里,因此无法至少一次不读入文件就无法跳转。你可以执行以下操作:

# Read in the file once and build a list of line offsetsline_offset = []offset = 0for line in file:    line_offset.append(offset)    offset += len(line)file.seek(0)# Now, to skip to line n (with the first line being line 0), just dofile.seek(line_offset[n])

c# – 如何跳转到RichTextBox中的特定行?

c# – 如何跳转到RichTextBox中的特定行?

我正在寻找一个示例代码如何跳转到 WPF中的RichTextBox的特定行.

我不知道如何做到这一点,在winForms中它非常简单,因为我可以自由设置SelectionStart和SelectionLength,与WPF不同,等效属性是只读的.

解决方法

您在API中有一些选项:

> LineDown
> ScrollToVerticalOffset
> ScrollToEnd

linux – 如何使用shell脚本将文本附加到文件中的特定行?

linux – 如何使用shell脚本将文本附加到文件中的特定行?

我有一个文本文件(file.txt),其内容类似于:

foo1 3464 
foo2 3696 
foo3 4562

它包含过程和相应的PID.

根据PID,我想使用shell脚本,在这个文件中追加一个字符串(运行/不运行).

例如,在上面的文件中,对于包含PID 3696的行,我想在末尾附加一个字符串“running”,以便该文件变为:

foo1 3464 
foo2 3696 running
foo3 4562

我该怎么做?

解决方法

$sed '/3696/ s/$/running/' file.txt 
foo1 3464 
foo2 3696 running
foo3 4562

要么

$sed 's/3696/& running/' file.txt 
foo1 3464 
foo2 3696 running 
foo3 4562

添加-i选项以将更改保存回file.txt.

perl – 如何在Unix中打印文件中的特定行?

perl – 如何在Unix中打印文件中的特定行?

我想从Unix中的文本文件中打印某些行.要打印的行号列在另一个文本文件中(每行一个).

有没有使用Perl或shell脚本快速完成此操作的方法?

解决方法

假设要打印的行号已排序.

open my $fh,'<','line_numbers' or die $!;
my @ln = <$fh>;
open my $tx,'text_file' or die $!;
foreach my $ln (@ln) {
  my $line;
  do {
    $line = <$tx>;
  } until $. == $ln and defined $line;
  print $line if defined $line;
}

python如何写入现有txt文件中的特定行

python如何写入现有txt文件中的特定行

我正在编写一个脚本,该脚本读取输入文件,获取值并需要在输出模板的特定位置(行)写入,我绝对是菜鸟,无法做到。它要么写在输出的第一行,要么写在最后一行。

打开的文件为“ r +”

使用的file.write(xyz)命令

关于如何向python解释以写入特定行的说法,例如。第17行(输出模板中的空白行)

编辑:

with open (MCNP_input, ''r+'') as M:           line_to_replace = 17           lines = M.readlines()           if len(lines) > int (line_to_replace):               lines[line_to_replace] = shape_sphere + radius + ''\n''               M.writelines(lines)

答案1

小编典典

您可以读取文件,然后写入某些特定行。

line_to_replace = 17 #the line we want to remplacemy_file = ''myfile.txt''with open(my_file, ''r'') as file:    lines = file.readlines()#now we have an array of lines. If we want to edit the line 17...if len(lines) > int(line_to_replace):    lines[line_to_replace] = ''The text you want here''with open(my_file, ''w'') as file:    file.writelines( lines )

关于Python-如何跳至巨大文本文件中的特定行?python跳转到指定行的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于c# – 如何跳转到RichTextBox中的特定行?、linux – 如何使用shell脚本将文本附加到文件中的特定行?、perl – 如何在Unix中打印文件中的特定行?、python如何写入现有txt文件中的特定行等相关知识的信息别忘了在本站进行查找喔。

本文标签: